﻿using System;
using System.IO;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;

using CE.Mail;
using CE.User;
using CE.Global;
using CE.Security;
using CE.InputOut;
using CE.Database;
using CE.CarInsurance;
using CXDecryption;

public partial class carinsurance_merchant_MerchantApplication : System.Web.UI.Page
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }
        if (!IsPostBack)
        {
            //bool test = SendTestAdmin();
            lblFinanceUserAlert.Text = "";
            ddlApplicationType.Items.Clear();
            ddlApplicationType.Items.Clear();
            ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeNew, "NEW"));
            ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeChangeBroker, "CHB"));
            lblNonGGStatus.Text = "0";
            lblPayError.Text = "";
            divCar.Visible = false;
            lblSearchMessage.Text = "";
            pnlCarDetails.Visible = false;
            txtCarId.Text = "";
            txtCEId.Text = "0";
            txtLastQuoteRefNo.Text = "";
            txtLastStep.Text = "";
            LoadOption();
            LoadGarageType();
            LoadInsuranceType();
            LoadVehicleType();
            LoadOccupation();
            LoadDOB();
            LoadCommanceDate();
            LoadFileUploadType();
            EnableOnOff(false);
            btnPaySubmit.Enabled = true;
            btnPayNew.Enabled = true;
            trInsurerEmail.Visible = false;
            rfvInsurerEmail.Enabled = false;
            revInsurerEmail.Enabled = false;
            chkApprove.Enabled = false;
            chkRefund.Enabled = false;
            lblLoadMessage.Text = string.Empty;
            string _IsEdit = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsNonGGEdit");
            if (_IsEdit == "1")
            {
                EnableOnOff(true);
            }
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
            ddlApplicationType_SelectedIndexChanged(null, null);

            txtAgentId.Text = Session[General.UserId].ToString();
            //txtAgentId.Text = "0";
            if (Request.QueryString["CEId"] != null)
            {
                txtCEId.Text = Request.QueryString["CEId"].ToString();

                string strSql = @"SELECT m.MerchantId, m.MerchantName FROM tblMerchantUser u INNER JOIN tblMerchant m 
                                ON u.MerchantId = m.MerchantId WHERE u.CEId = " + txtCEId.Text.Trim();
                MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
                DataTable dtItemResult = _db.GetDataTable(strSql);

                if (dtItemResult != null && dtItemResult.Rows.Count > 0)
                {
                    if (dtItemResult.Rows[0]["MerchantId"] != DBNull.Value)
                    {
                        txtMerchantId.Text = dtItemResult.Rows[0]["MerchantId"].ToString();
                    }
                    if (dtItemResult.Rows[0]["MerchantName"] != DBNull.Value)
                    {
                        lblPageName.Text += " - " + dtItemResult.Rows[0]["MerchantName"].ToString();
                    }
                }
            }

            if (Request.QueryString["refno"] != null)
            {
                txtSearch.Text = Request.QueryString["refno"].ToString();
                btnSearch_Click(sender, e);
            }

        }
        else
        {
            lblNewCallMessage.Text = "";
        }
    }

    private DataTable CheckCarId(string strCarId)
    {
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        DataTable _dt = new DataTable();
        string strSql = "SELECT CD.CarId, CP.Info8, CP.refceuserid FROM tblMerchantCarDetail CD INNER JOIN tblMerchantCarPolicy CP " +
                            "ON CD.refceuserid = CP.refceuserid AND CD.CarId = CP.CECarId " +
                            "WHERE CD.[Status] = 1 AND CD.CarId = " + strCarId;
        _dt = _db.GetDataTable(strSql);
        _db = null;
        return _dt;

    }

    private string GetLastYearRefNo(string strCarId, string strCEId)
    {
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        string strSql = "SELECT Info7 FROM tblMerchantCarPolicy WHERE Info7 IS NOT NULL AND LEN(Info7) > 0 AND CECarId = " + strCarId + " AND RefCEUserId = " + strCEId;
        string _lastYearRefNo = string.Empty;
        object _objLastYearRefNo = _db.ExecuteScalarSqlStatement(strSql);

        if (_objLastYearRefNo != null)
        {
            _lastYearRefNo = _objLastYearRefNo.ToString();
        }

        _db = null;
        _objLastYearRefNo = null;

        return _lastYearRefNo;

    }

    private string GetLastYearPolicyNo(string strCarId, string strCEId)
    {
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        string strSql = "SELECT Remarks FROM tblMerchantTransaction ";
        strSql += " WHERE TransactionTypeId = 300 AND CarId = " + strCarId + " AND RefCEUserId = " + strCEId;
        string _lastYearPolicyNo = string.Empty;
        object _objLastYearPolicyNo = _db.ExecuteScalarSqlStatement(strSql);

        if (_objLastYearPolicyNo != null)
        {
            _lastYearPolicyNo = _objLastYearPolicyNo.ToString();
        }

        _db = null;
        _objLastYearPolicyNo = null;

        return _lastYearPolicyNo;

    }

    protected void btnAppSummary_Click(object sender, EventArgs e)
    {
        Response.Redirect("MerchantApplicationStatus.aspx?CEId=" + txtCEId.Text.Trim() + "&search=" + lblUpRefNo.Text);
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        txtAgentRemarkDetails.Text = "";
        divPayList.Visible = false;
        grvPayment.DataSource = null;
        grvPayment.DataBind();
        lblNonGGStatus.Text = "0";
        pnlOptionMessage.Visible = false;
        lblOptionError.Text = string.Empty;
        lblOptionMessage.Text = string.Empty;
        pnlDetails.Visible = false;
        pnlPayment.Visible = false;
        pnlCarDetails.Visible = false;
        pnlApplicationCancel.Visible = false;
        pnlApplicationRetrieve.Visible = false;
        pnlUploadFileList.Visible = false;
        LoadOption();
        if (Server.HtmlEncode(txtSearch.Text).Trim() != "" && Server.HtmlEncode(txtSearch.Text).Trim().Length > 4)
        {
            txtGG.Text = "PROVIDER";
            if (txtSearch.Text.Trim().Substring(0, 2) == "GG")
            {
                txtGG.Text = "GGSPECIAL";
            }
            if (txtSearch.Text.Trim().Substring(0, 1) == "M")
            {
                txtGG.Text = "MERCHANT";
            }
            if (CheckSelectedItem(Server.HtmlEncode(txtSearch.Text).Trim().ToUpper()))
            {
                txtCarId.Text = CE.Global.General.GetCarId(Server.HtmlEncode(txtSearch.Text).Trim());
                DataTable _dtCarCustomer = new DataTable();
                _dtCarCustomer = CheckCarId(txtCarId.Text);
                if (_dtCarCustomer != null && _dtCarCustomer.Rows.Count > 0)
                {
                    txtCarId.Text = _dtCarCustomer.Rows[0]["CarId"].ToString();
                    txtCEId.Text = _dtCarCustomer.Rows[0]["RefCEUserid"].ToString();
                    lblTESCO200.Text = _dtCarCustomer.Rows[0]["Info8"].ToString();
                }

                if (txtCarId.Text != string.Empty && txtCEId.Text != string.Empty && txtCarId.Text != "0" && txtCEId.Text != "0")
                {
                    LoadApplicationDetails();

                    lblMailingStatus.Text = "0";
                    if (!CheckApplicationProcessStatus(lblUpRefNo.Text.Trim().ToUpper(), "MAILING"))
                    {
                        lblMailingStatus.Text = "1";
                    }
                }
                else
                {
                    lblSearchMessage.Text = Resources.General.CheckRefNo;
                    divCar.Visible = false;
                }

                if (txtCEId.Text.Trim() != "0" && txtMerchantId.Text == "")
                {
                    string strSql = @"SELECT m.MerchantId, m.MerchantName FROM tblMerchantUser u INNER JOIN tblMerchant m 
                                ON u.MerchantId = m.MerchantId WHERE u.CEId = " + txtCEId.Text.Trim();
                    MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
                    DataTable dtItemResult = _db.GetDataTable(strSql);

                    if (dtItemResult != null && dtItemResult.Rows.Count > 0)
                    {
                        if (dtItemResult.Rows[0]["MerchantId"] != DBNull.Value)
                        {
                            txtMerchantId.Text = dtItemResult.Rows[0]["MerchantId"].ToString();
                        }
                        if (dtItemResult.Rows[0]["MerchantName"] != DBNull.Value)
                        {
                            lblPageName.Text += " - " + dtItemResult.Rows[0]["MerchantName"].ToString();
                        }
                    }
                }
            }
            else
            {
                lblSearchMessage.Text = Resources.General.CheckRefNo;
                divCar.Visible = false;
            }
        }
        else if (Server.HtmlEncode(txtSearch.Text).Trim().Length > 1 && Server.HtmlEncode(txtSearch.Text).Trim().Length <= 4)
        {
            lblSearchMessage.Text = Resources.General.CheckRefNo;
            divCar.Visible = false;
        }
        lblLoadMessage.Text = string.Empty;
    }

    private void LoadDate()
    {
        Int32 intStartYear = dateTimeNow.Year - 50; //DateTime.Now.Year
        Int32 intEndYear = dateTimeNow.Year + 50; //DateTime.Now.Year
        if (intStartYear == 0) intStartYear = dateTimeNow.Year - 75; //DateTime.Now.Year
        if (intEndYear == 0) intEndYear = dateTimeNow.Year + 20; //DateTime.Now.Year

        ddlCommenceYear.Items.Clear();

        for (int i = intEndYear; i >= intStartYear; i--)
        {
            if (lblLangOption.Text == "1")
            {
                ddlCommenceYear.Items.Add(new ListItem((i + 543).ToString(), i.ToString()));
            }
            else if (lblLangOption.Text == "2")
            {
                ddlCommenceYear.Items.Add(i.ToString());
            }
        }
        lblLoadMessage.Text = string.Empty;
    }

    private void LoadOption()
    {
        if (Session[CE.Global.General.UserRole] != null)
        {
            if (Session[CE.Global.General.UserRole].ToString() == "100")
            {
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.MoreDetails, "EDIT"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Payment, "PAYM"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.CancelRejectApplication, "ACNL"));
                ddlOption.SelectedIndex = 0;
            }
            else if (Session[CE.Global.General.UserRole].ToString() == "200")
            {
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.MoreDetails, "EDIT"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Payment, "PAYM"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.UploadFile, "UPLD"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.CancelRejectApplication, "ACNL"));
                ddlOption.SelectedIndex = 0;
            }
            else
            {
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.MoreDetails, "EDIT"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Payment, "PAYM"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.UploadFile, "UPLD"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.CancelRejectApplication, "ACNL"));
                ddlOption.SelectedIndex = 0;
            }
            lblLoadMessage.Text = string.Empty;
        }

    }

    public void LoadApplicationDetails()
    {
        ClearFields();
        if (txtLastQuoteRefNo.Text != txtSearch.Text)
        {
            txtLastStep.Text = "";
            txtLastQuoteRefNo.Text = "";
        }
        lblNonGGStatus.Text = "0";
        string _ProviderRefCode = txtSearch.Text.Trim();
        string PID = "0";
        string LYPID = "0";
        if (_ProviderRefCode.Substring(0, 2) == "GG")
        {
            PID = _ProviderRefCode.Substring(2, 2);
        }

        if (_ProviderRefCode.Substring(0, 1) == "M")
        {
            _ProviderRefCode = _ProviderRefCode.Substring(4, 2);
        }
        else
        {
            _ProviderRefCode = _ProviderRefCode.Substring(0, 3);
        }
        DataSet _dsApplication = new DataSet();
        MerchantPackageDB _nonggpackagedb = new MerchantPackageDB();
        _dsApplication = _nonggpackagedb.GetCarDetails(Convert.ToInt64(txtCarId.Text.Trim()), Convert.ToInt64(txtCEId.Text.Trim()));
        if (_dsApplication != null && _dsApplication.Tables.Count > 0 && _dsApplication.Tables[0].Rows.Count > 0)
        {
            txtUserTypeId.Text = _dsApplication.Tables[0].Rows[0]["UsrTypeId"].ToString();
            if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count > 0)
            {
                DateTime _LastUpdateDate = new DateTime();
                _LastUpdateDate = Convert.ToDateTime(_dsApplication.Tables[2].Rows[0]["ModifiedDate"].ToString());
                lblLastUpdate.Text = Resources.General.LastUpdated + " : " + _LastUpdateDate.ToString("dd/MMM/yyyy hh:mm tt");
            }
            else
            {
                lblLastUpdate.Text = Resources.General.HaveNotSubmit;
            }

            lblSearchMessage.Text = "";
            if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count > 0)
            {
                divCar.Visible = true;
                LoadNonGGApplicationDetails(_dsApplication);
            }
            else if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count == 0)
            {
                #region Assign Values
                bool ProviderStatus = false;
                if (PID != "0" && _dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString() == PID)
                {
                    ProviderStatus = true;
                }
                else if (_dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString() == CE.Global.General.GetProviderId(_ProviderRefCode))
                {
                    ProviderStatus = true;
                }
                if (ProviderStatus == true)
                {
                    if (_dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString() == "43")
                    {
                        trInsurerEmail.Visible = true;
                        rfvInsurerEmail.Enabled = true;
                        revInsurerEmail.Enabled = true;
                        txtInsurerEmail.Text = "support@gluaygluay.com";
                    }
                    else
                    {
                        trInsurerEmail.Visible = false;
                        rfvInsurerEmail.Enabled = false;
                        revInsurerEmail.Enabled = false;
                        txtInsurerEmail.Text = "";
                    }
                    divCar.Visible = true;
                    ddlCustomerType.SelectedIndex = 0;
                    chkIsCreditCardOwner.Checked = false;
                    if (_dsApplication.Tables[0].Rows[0]["Ninfo5"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["Ninfo5"].ToString() != string.Empty)
                    {
                        if (_dsApplication.Tables[0].Rows[0]["Ninfo5"].ToString() == "1")
                        {
                            chkIsCreditCardOwner.Checked = true;
                        }
                    }
                    if (_dsApplication.Tables[0].Rows[0]["Info7"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["Info7"].ToString() != string.Empty)
                    {
                        if (_dsApplication.Tables[0].Rows[0]["Info6"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["Info6"].ToString() != string.Empty)
                        {
                            txtLastYearCarId.Text = _dsApplication.Tables[0].Rows[0]["Info6"].ToString();
                        }
                        lblLastYearRefNo.Text = _dsApplication.Tables[0].Rows[0]["Info7"].ToString();
                        txtLastYearRefNo.Text = lblLastYearRefNo.Text;

                        lblLastYearPolicyNo.Text = string.Empty;
                        if (txtLastYearRefNo.Text.Trim().Length > 0)
                        {
                            lblRenewalMessage.Text = "Renewal App Details. Last Year Ref.No [ " + txtLastYearRefNo.Text + " ]";
                            ClientScript.RegisterStartupScript(lblLastUpdate.GetType(), "DownloadPremiumAlert", "alert('" + lblRenewalMessage.Text + "!');", true);


                            string _LstYrProviderRefCode = txtLastYearRefNo.Text.Trim();
                            if (_LstYrProviderRefCode.Substring(0, 2) == "GG")
                            {
                                LYPID = _LstYrProviderRefCode.Substring(2, 2);
                            }
                            _LstYrProviderRefCode = _LstYrProviderRefCode.Substring(0, 3);
                            bool LYProviderStatus = false;
                            if (PID != "0" && LYPID != "0" && PID == LYPID)
                            {
                                LYProviderStatus = true;
                            }
                            else if (CE.Global.General.GetProviderId(_ProviderRefCode) == CE.Global.General.GetProviderId(_LstYrProviderRefCode))
                            {
                                LYProviderStatus = true;
                            }
                            if (LYProviderStatus == true)
                            {
                                ddlApplicationType.Items.Clear();
                                ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeRenewalSameInsurer, "REN"));
                                ddlApplicationType.Text = "REN";
                                ddlApplicationType_SelectedIndexChanged(null, null);
                                lblLastYearPolicyNo.Text = GetLastYearPolicyNo(txtLastYearCarId.Text, txtUserId.Text);
                                txtLastYearPolicyNo.Text = lblLastYearPolicyNo.Text;
                            }
                            else
                            {
                                ddlApplicationType.Items.Clear();
                                ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeRenewalOtherInsurer, "RNO"));
                                ddlApplicationType.Text = "RNO";
                                ddlApplicationType_SelectedIndexChanged(null, null);
                            }
                        }
                        else
                        {
                            ddlApplicationType.Items.Clear();
                            ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeNew, "NEW"));
                            ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeChangeBroker, "CHB"));
                        }
                    }

                    if (_dsApplication.Tables[0].Rows[0]["ModificationAmount"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString() != string.Empty)
                    {
                        trModificationAmount.Visible = true;
                        txtModificationAmount.Text = _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString();
                    }
                    else
                    {
                        trModificationAmount.Visible = false;
                        txtModificationAmount.Text = "";
                    }

                    if (_dsApplication != null && _dsApplication.Tables.Count > 4 && _dsApplication.Tables[4].Rows.Count > 0)
                    {
                        if (_dsApplication.Tables[4].Rows[0]["Name"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["Name"].ToString() != string.Empty)
                        {
                            txtCustomerName.Text = _dsApplication.Tables[4].Rows[0]["Name"].ToString();
                        }
                        else
                        {
                            txtCustomerName.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                        }
                    }
                    else
                    {
                        txtCustomerName.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                    }
                    lblUpApplicantName.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                    txtInsuredPerson.Text = _dsApplication.Tables[0].Rows[0]["InsuredPerson"].ToString();
                    txtContactNumber.Text = _dsApplication.Tables[0].Rows[0]["Mobile"].ToString();
                    if (_dsApplication.Tables[0].Rows[0]["OfficePhoneNo"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["OfficePhoneNo"].ToString() != string.Empty)
                    {
                        txtOtherContactNumber.Text = _dsApplication.Tables[0].Rows[0]["OfficePhoneNo"].ToString();
                    }
                    txtProviderId.Text = _dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString();
                    LoadLableColor();
                    txtNewQuoteRefNo.Text = CE.Global.General.GetMerchantReferenceNumber(txtCarId.Text.Trim(), txtProviderId.Text.Trim(), txtMerchantId.Text.Trim());
                    if (txtGG.Text.Trim() == "GGSPECIAL")
                    {
                        txtNewQuoteRefNo.Text = CE.Global.General.GetGGReferenceNumber(txtCarId.Text.Trim(), txtProviderId.Text.Trim());
                    }
                    //txtUserId.Text = _dsApplication.Tables[0].Rows[0]["RefCEUserId"].ToString();
                    txtCarModelYear.Text = _dsApplication.Tables[0].Rows[0]["ManufactYear"].ToString();
                    txtCarMakeModel.Text = _dsApplication.Tables[0].Rows[0]["MakeModelDesc"].ToString();
                    if (_dsApplication.Tables[0].Rows[0]["InsuranceType"] != DBNull.Value)
                    {
                        ddlInsuranceType.Text = _dsApplication.Tables[0].Rows[0]["InsuranceType"].ToString();
                    }
                    if (_dsApplication.Tables[0].Rows[0]["VehicleType"] != DBNull.Value)
                    {
                        ddlVehicleType.Text = _dsApplication.Tables[0].Rows[0]["VehicleType"].ToString();
                    }
                    if (_dsApplication.Tables[0].Rows[0]["GarageType"] != DBNull.Value)
                    {
                        ddlGarageType.Text = _dsApplication.Tables[0].Rows[0]["GarageType"].ToString();
                    }
                    ddlNCB.Text = _dsApplication.Tables[0].Rows[0]["NCDPercent"].ToString();
                    //string _sumInsured = string.Empty;
                    //Int32 _outSumInsurred = 0;
                    //float _outfloatSumInsurred = 0.0f;
                    //_sumInsured = _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
                    //_sumInsured = _sumInsured.Replace(",", "");
                    //if (_sumInsured != string.Empty && float.TryParse(_sumInsured, out _outfloatSumInsurred))
                    //{
                    //    Int32.TryParse(_outfloatSumInsurred.ToString("#"), out _outSumInsurred);
                    //    _sumInsured = _outSumInsurred.ToString();
                    //}
                    //else
                    //{
                    //    _sumInsured = "0";
                    //}
                    string _sumInsured = string.Empty;
                    _sumInsured = _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
                    decimal _outSumInsurred = 0;
                    if (!decimal.TryParse(_sumInsured, out _outSumInsurred))
                    {
                        _sumInsured = "0";
                    }
                    else
                    {
                        _sumInsured = _outSumInsurred.ToString("#0");
                    }
                    txtSumInsured.Text = _sumInsured.ToString();// _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
                    txtInsurancePremium.Text = _dsApplication.Tables[0].Rows[0]["Premium"].ToString();
                    txtTotalPremium.Text = _dsApplication.Tables[0].Rows[0]["TotalPremium"].ToString();
                    txtCollectedAmount.Text = _dsApplication.Tables[0].Rows[0]["FinalAnnualPremium"].ToString();
                    lblUpPremium.Text = _dsApplication.Tables[0].Rows[0]["FinalAnnualPremium"].ToString();
                    txtCTPL.Text = _dsApplication.Tables[0].Rows[0]["CTPL"].ToString();
                    txtCurrentInsurer.Text = _dsApplication.Tables[0].Rows[0]["CurrentInsurer"].ToString();
                    txtPlateNumber.Text = _dsApplication.Tables[0].Rows[0]["CarPlate"].ToString();

                    if (_dsApplication.Tables[0].Rows[0]["IsCTPL"].ToString() == "False" || _dsApplication.Tables[0].Rows[0]["IsCTPL"].ToString() == "0")
                    {
                        ddlCTPL.Text = "0";
                    }
                    else
                    {
                        ddlCTPL.Text = "1";
                    }

                    if (_dsApplication.Tables[0].Rows[0]["Gender"] != DBNull.Value)
                    {
                        ddlGender.Text = _dsApplication.Tables[0].Rows[0]["Gender"].ToString();
                    }
                    if (_dsApplication.Tables[0].Rows[0]["OccupationId"] != DBNull.Value)
                    {
                        ddlOccupation.Text = _dsApplication.Tables[0].Rows[0]["OccupationId"].ToString();
                    }
                    txtInsuranceCompany.Text = _dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();
                    txtPackage.Text = _dsApplication.Tables[0].Rows[0]["Package"].ToString();
                    ddlNamedDriver.Text = _dsApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
                    ddlNamedDriver_SelectedIndexChanged(null, null);
                    txtDriverId1.Text = "0";
                    txtDriverId2.Text = "0";
                    DateTime Commdate = dateTimeNow; //DateTime.Now;
                    if (_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"].ToString() != string.Empty)
                    {
                        Commdate = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["CoverageCommenceDate"].ToString());
                    }
                    AssignDate(Commdate.Day, ddlCommenceDay);
                    AssignMonth(Commdate.Month, ddlCommenceMonth);
                    AssignYear(Commdate.Year, ddlCommenceYear);

                    AssignDate(Commdate.Day, ddlPolicyDay);
                    AssignMonth(Commdate.Month, ddlPolicyMonth);
                    AssignYear(Commdate.Year, ddlPolicyYear);

                    DateTime DOB = dateTimeNow; //DateTime.Now;
                    if (_dsApplication.Tables[0].Rows[0]["DOB"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["DOB"].ToString() != string.Empty)
                    {
                        DOB = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["DOB"].ToString());
                    }
                    AssignDate(DOB.Day, ddlDOBDay);
                    AssignMonth(DOB.Month, ddlDOBMonth);
                    AssignYear(DOB.Year, ddlDOBYear);
                    DateTime DriverDOB1 = dateTimeNow.AddYears(-20); //DateTime.Now.AddYears(-20);
                    DateTime DriverDOB2 = dateTimeNow.AddYears(-20); //DateTime.Now.AddYears(-20);
                    if (_dsApplication.Tables.Count > 1)
                    {
                        if (_dsApplication.Tables[1].Rows.Count > 0 && _dsApplication.Tables[1].Rows[0]["CarDriverId"] != DBNull.Value && _dsApplication.Tables[1].Rows[0]["CarDriverId"].ToString() != string.Empty)
                        {
                            txtDriverId1.Text = _dsApplication.Tables[1].Rows[0]["CarDriverId"].ToString();
                        }
                        if (_dsApplication.Tables[1].Rows.Count > 0 && _dsApplication.Tables[1].Rows[0]["DOB"] != DBNull.Value && _dsApplication.Tables[1].Rows[0]["DOB"].ToString() != string.Empty)
                        {
                            DriverDOB1 = Convert.ToDateTime(_dsApplication.Tables[1].Rows[0]["DOB"].ToString());
                        }
                        if (_dsApplication.Tables[1].Rows.Count > 0 && _dsApplication.Tables[1].Rows[1]["CarDriverId"] != DBNull.Value && _dsApplication.Tables[1].Rows[1]["CarDriverId"].ToString() != string.Empty)
                        {
                            txtDriverId2.Text = _dsApplication.Tables[1].Rows[1]["CarDriverId"].ToString();
                        }
                        if (_dsApplication.Tables[1].Rows.Count > 1 && _dsApplication.Tables[1].Rows[1]["DOB"] != DBNull.Value && _dsApplication.Tables[1].Rows[1]["DOB"].ToString() != string.Empty)
                        {
                            DriverDOB2 = Convert.ToDateTime(_dsApplication.Tables[1].Rows[1]["DOB"].ToString());
                        }

                    }
                    AssignDate(DriverDOB1.Day, ddlDriver1DOBDay);
                    AssignMonth(DriverDOB1.Month, ddlDriver1DOBMonth);
                    AssignYear(DriverDOB1.Year, ddlDriver1DOBYear);
                    AssignDate(DriverDOB2.Day, ddlDriver2DOBDay);
                    AssignMonth(DriverDOB2.Month, ddlDriver2DOBMonth);
                    AssignYear(DriverDOB2.Year, ddlDriver2DOBYear);
                    if (ddlNamedDriver.Text == "0")
                    {
                        rfvDriverFirst.Enabled = false;
                        revDriverFirst.Enabled = false;
                        rfvDriver1IDNo.Enabled = false;
                        rfvDriver1LicenseNo.Enabled = false;
                        rfvDriverTwo.Enabled = false;
                        revDriverTwo.Enabled = false;
                        rfvDriver2IDNo.Enabled = false;
                        rfvDriver2LicenseNo.Enabled = false;
                    }
                    if (ddlNamedDriver.Text == "1")
                    {
                        rfvDriverFirst.Enabled = true;
                        revDriverFirst.Enabled = true;
                        rfvDriver1IDNo.Enabled = true;
                        rfvDriver1LicenseNo.Enabled = true;
                        rfvDriverTwo.Enabled = false;
                        revDriverTwo.Enabled = false;
                        rfvDriver2IDNo.Enabled = false;
                        rfvDriver2LicenseNo.Enabled = false;
                    }
                    if (ddlNamedDriver.Text == "2")
                    {
                        rfvDriverFirst.Enabled = true;
                        revDriverFirst.Enabled = true;
                        rfvDriver1IDNo.Enabled = true;
                        rfvDriver1LicenseNo.Enabled = true;
                        rfvDriverTwo.Enabled = true;
                        revDriverTwo.Enabled = true;
                        rfvDriver2IDNo.Enabled = true;
                        rfvDriver2LicenseNo.Enabled = true;
                    }

                    if (_dsApplication.Tables.Count > 4 && _dsApplication.Tables[4].Rows.Count > 0)
                    {
                        if (_dsApplication.Tables[4].Rows[0]["Name"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["Name"].ToString() != string.Empty)
                        {
                            txtCustomerName.Text = _dsApplication.Tables[4].Rows[0]["Name"].ToString();
                        }
                        if (_dsApplication.Tables[4].Rows[0]["BeneficiaryName"] != DBNull.Value)
                            txtBeneficiary.Text = _dsApplication.Tables[4].Rows[0]["BeneficiaryName"].ToString();
                        if (_dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"].ToString() != string.Empty
                            && _dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"].ToString() != "true" && _dsApplication.Tables[4].Rows[0]["IsMailingAddressDiff"].ToString() != "1")
                        {
                            txtCurrentAddress.Text = _dsApplication.Tables[4].Rows[0]["PresentAddress"].ToString();
                            txtSubDistrict.Text = _dsApplication.Tables[4].Rows[0]["SubDistrict"].ToString();
                            txtStateProvince.Text = _dsApplication.Tables[4].Rows[0]["District"].ToString();
                            txtProvince.Text = _dsApplication.Tables[4].Rows[0]["Province"].ToString();
                            txtPostalCode.Text = _dsApplication.Tables[4].Rows[0]["PostalCode"].ToString();
                        }
                        else
                        {
                            txtCurrentAddress.Text = _dsApplication.Tables[4].Rows[0]["MailingAddress"].ToString();
                            txtSubDistrict.Text = _dsApplication.Tables[4].Rows[0]["MailingSubDistrict"].ToString();
                            txtStateProvince.Text = _dsApplication.Tables[4].Rows[0]["MailingDistrict"].ToString();
                            txtProvince.Text = _dsApplication.Tables[4].Rows[0]["MailingProvince"].ToString();
                            txtPostalCode.Text = _dsApplication.Tables[4].Rows[0]["MailingPostalCode"].ToString();
                        }
                        if (_dsApplication.Tables.Count > 5 && _dsApplication.Tables[5].Rows.Count > 0)
                        {
                            txtPackage.Text = _dsApplication.Tables[5].Rows[0]["CoverTypeDesc"].ToString();
                        }
                        if (_dsApplication.Tables[4].Rows[0]["EngineNumber"] != DBNull.Value)
                            txtEngineNumber.Text = _dsApplication.Tables[4].Rows[0]["EngineNumber"].ToString();
                        if (_dsApplication.Tables[4].Rows[0]["ChassisNumber"] != DBNull.Value)
                            txtChassisNumber.Text = _dsApplication.Tables[4].Rows[0]["ChassisNumber"].ToString();
                        if (_dsApplication.Tables[4].Rows[0]["CarPlate"] != DBNull.Value)
                            txtPlateNumber.Text = _dsApplication.Tables[4].Rows[0]["CarPlate"].ToString().ToUpper();
                        if (_dsApplication.Tables[4].Rows[0]["CarPlateProvince"] != DBNull.Value)
                            txtRegistrationProvince.Text = _dsApplication.Tables[4].Rows[0]["CarPlateProvince"].ToString();

                        DateTime _CreateDate = Convert.ToDateTime(_dsApplication.Tables[4].Rows[0]["CreatedDate"].ToString());
                        if (ddlApplicationDay.Items.Count > 0)
                            ddlApplicationDay.Items.Clear();
                        ddlApplicationDay.Items.Add(new ListItem(_CreateDate.Day.ToString("00"), _CreateDate.Day.ToString("00")));
                        if (ddlApplicationMonth.Items.Count > 0)
                            ddlApplicationMonth.Items.Clear();
                        ddlApplicationMonth.Items.Add(new ListItem(_CreateDate.Month.ToString("00"), _CreateDate.Month.ToString("00")));
                        if (ddlApplicationYear.Items.Count > 0)
                            ddlApplicationYear.Items.Clear();
                        ddlApplicationYear.Items.Add(new ListItem(_CreateDate.Year.ToString("0000"), _CreateDate.Year.ToString("0000")));
                    }
                    else
                    {
                        DateTime _CreateDate = Convert.ToDateTime(_dsApplication.Tables[0].Rows[0]["CreatedDate"].ToString());
                        if (ddlApplicationDay.Items.Count > 0)
                            ddlApplicationDay.Items.Clear();
                        ddlApplicationDay.Items.Add(new ListItem(_CreateDate.Day.ToString("00"), _CreateDate.Day.ToString("00")));
                        if (ddlApplicationMonth.Items.Count > 0)
                            ddlApplicationMonth.Items.Clear();
                        ddlApplicationMonth.Items.Add(new ListItem(_CreateDate.Month.ToString("00"), _CreateDate.Month.ToString("00")));
                        if (ddlApplicationYear.Items.Count > 0)
                            ddlApplicationYear.Items.Clear();
                        ddlApplicationYear.Items.Add(new ListItem(_CreateDate.Year.ToString("0000"), _CreateDate.Year.ToString("0000")));
                    }
                }
                #endregion
            }
            else
            {
                lblSearchMessage.Text = Resources.General.CheckRefNo;
                divCar.Visible = false;
            }
            LoadLastYearApplicationDetails();
        }
        else
        {
            lblSearchMessage.Text = Resources.General.CheckRefNo;
            divCar.Visible = false;
        }
        if (txtCEId.Text != "" && txtProviderId.Text != "")
        {
            GetCarMoreDetails();
        }
    }

    public void LoadNonGGApplicationDetails(DataSet dsApplication)
    {
        //ClearFields();
        string _ProviderRefCode = txtSearch.Text.Trim();
        string PID = "0";
        if (_ProviderRefCode.Substring(0, 2) == "GG")
        {
            PID = _ProviderRefCode.Substring(2, 2);
        }
        _ProviderRefCode = _ProviderRefCode.Substring(0, 3);
        if (dsApplication != null && dsApplication.Tables.Count > 2 && dsApplication.Tables[2].Rows.Count > 0)
        {
            lblSearchMessage.Text = "";
            lblNonGGStatus.Text = "1";
            #region Assign Values

            if (dsApplication.Tables[2].Rows[0]["ProviderCompanyId"].ToString() == "43")
            {
                trInsurerEmail.Visible = true;
                rfvInsurerEmail.Enabled = true;
                revInsurerEmail.Enabled = true;
                if (dsApplication.Tables[2].Rows[0]["Info3"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info3"].ToString() != string.Empty)
                {
                    txtInsurerEmail.Text = dsApplication.Tables[2].Rows[0]["Info3"].ToString();
                }
                else
                {
                    txtInsurerEmail.Text = "support@gluaygluay.com";
                }
            }
            else
            {
                trInsurerEmail.Visible = false;
                rfvInsurerEmail.Enabled = false;
                revInsurerEmail.Enabled = false;
                txtInsurerEmail.Text = "";
            }
            lblAgentId.Text = "0";
            lblAdminId.Text = "0";
            chkIsCreditCardOwner.Checked = false;
            if (dsApplication.Tables[0].Rows[0]["Ninfo5"] != DBNull.Value && dsApplication.Tables[0].Rows[0]["Ninfo5"].ToString() != string.Empty)
            {
                if (dsApplication.Tables[0].Rows[0]["Ninfo5"].ToString() == "1")
                {
                    chkIsCreditCardOwner.Checked = true;
                }
            }
            chkPromotion.Checked = false;
            if (dsApplication.Tables[2].Rows[0]["PromotionCode"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["PromotionCode"].ToString() != string.Empty)
            {
                if (dsApplication.Tables[2].Rows[0]["PromotionCode"].ToString() == "1")
                {
                    chkPromotion.Checked = true;
                }
            }
            if (dsApplication.Tables[0].Rows[0]["Info7"] != DBNull.Value && dsApplication.Tables[0].Rows[0]["Info7"].ToString() != string.Empty)
            {
                lblLastYearRefNo.Text = dsApplication.Tables[0].Rows[0]["Info7"].ToString();
                txtLastYearRefNo.Text = lblLastYearRefNo.Text;
                if (txtLastYearRefNo.Text.Trim().Length > 0)
                {
                    lblRenewalMessage.Text = "Renewal App Details. Last Year Ref.No [ " + txtLastYearRefNo.Text + " ]";
                    ClientScript.RegisterStartupScript(lblLastUpdate.GetType(), "DownloadPremiumAlert", "alert('" + lblRenewalMessage.Text + "!');", true);
                }
            }
            if (dsApplication.Tables[2].Rows[0]["Info1"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info1"].ToString() != string.Empty)
            {
                if (dsApplication.Tables[2].Rows[0]["Info1"].ToString().ToUpper() == "REN")
                {
                    ddlApplicationType.Items.Clear();
                    ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeRenewalSameInsurer, "REN"));
                    ddlApplicationType.Text = dsApplication.Tables[2].Rows[0]["Info1"].ToString();
                    ddlApplicationType_SelectedIndexChanged(null, null);
                }
                else if (dsApplication.Tables[2].Rows[0]["Info1"].ToString().ToUpper() == "RNO")
                {
                    ddlApplicationType.Items.Clear();
                    ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeRenewalOtherInsurer, "RNO"));
                    ddlApplicationType.Text = dsApplication.Tables[2].Rows[0]["Info1"].ToString();
                    ddlApplicationType_SelectedIndexChanged(null, null);
                }
                else
                {
                    ddlApplicationType.Items.Clear();
                    ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeNew, "NEW"));
                    ddlApplicationType.Items.Add(new ListItem(Resources.Proposal.AppTypeChangeBroker, "CHB"));
                    ddlApplicationType.Text = dsApplication.Tables[2].Rows[0]["Info1"].ToString();
                    ddlApplicationType_SelectedIndexChanged(null, null);
                }
            }
            if (dsApplication.Tables[2].Rows[0]["Info2"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info2"].ToString() != string.Empty)
            {
                txtLastYearPolicyNo.Text = dsApplication.Tables[2].Rows[0]["Info2"].ToString();
                lblLastYearPolicyNo.Text = dsApplication.Tables[2].Rows[0]["Info2"].ToString();
            }

            if (dsApplication.Tables[2].Rows[0]["Info4"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info4"].ToString() != string.Empty)
            {
                trModificationAmount.Visible = true;
                txtModificationAmount.Text = dsApplication.Tables[2].Rows[0]["Info4"].ToString();
            }
            else
            {
                trModificationAmount.Visible = false;
                txtModificationAmount.Text = "";
            }

            if (dsApplication.Tables[2].Rows[0]["Info8"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["Info8"].ToString() != string.Empty)
            {
                txtAgentRemarkDetails.Text = dsApplication.Tables[2].Rows[0]["Info8"].ToString();
            }
            else
            {
                txtAgentRemarkDetails.Text = "";
            }


            if (dsApplication.Tables[2].Rows[0]["AgentId"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["AgentId"].ToString() != string.Empty)
            {
                lblAgentId.Text = dsApplication.Tables[2].Rows[0]["AgentId"].ToString();
            }
            if (dsApplication.Tables[2].Rows[0]["AdminId"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["AdminId"].ToString() != string.Empty)
            {
                lblAdminId.Text = dsApplication.Tables[2].Rows[0]["AdminId"].ToString();
            }
            txtCarModelYear.Text = dsApplication.Tables[2].Rows[0]["CarYear"].ToString();
            txtCarMakeModel.Text = dsApplication.Tables[2].Rows[0]["CarModel"].ToString();
            if (dsApplication.Tables[2].Rows[0]["InsuranceType"] != DBNull.Value)
            {
                ddlInsuranceType.Text = dsApplication.Tables[2].Rows[0]["InsuranceType"].ToString();
            }
            if (dsApplication.Tables[2].Rows[0]["VehicleType"] != DBNull.Value)
            {
                ddlVehicleType.Text = dsApplication.Tables[2].Rows[0]["VehicleType"].ToString();
            }
            if (dsApplication.Tables[2].Rows[0]["GarageType"] != DBNull.Value)
            {
                ddlGarageType.Text = dsApplication.Tables[2].Rows[0]["GarageType"].ToString();
            }
            DateTime Commdate = dateTimeNow; //DateTime.Now;
            if (dsApplication.Tables[2].Rows[0]["CoverageStart"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["CoverageStart"].ToString() != string.Empty)
            {
                Commdate = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["CoverageStart"].ToString());
            }
            AssignDate(Commdate.Day, ddlCommenceDay);
            AssignMonth(Commdate.Month, ddlCommenceMonth);
            AssignYear(Commdate.Year, ddlCommenceYear);
            DateTime policy = dateTimeNow; //DateTime.Now;
            if (dsApplication.Tables[2].Rows[0]["CTPLStart"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["CTPLStart"].ToString() != string.Empty)
            {
                policy = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["CTPLStart"].ToString());
            }
            AssignDate(policy.Day, ddlPolicyDay);
            AssignMonth(policy.Month, ddlPolicyMonth);
            AssignYear(policy.Year, ddlPolicyYear);



            string _sumInsured = string.Empty;
            _sumInsured = dsApplication.Tables[2].Rows[0]["SumInsured"].ToString();
            decimal _outSumInsurred = 0;
            if (!decimal.TryParse(_sumInsured, out _outSumInsurred))
            {
                _sumInsured = "0";
            }
            else
            {
                _sumInsured = _outSumInsurred.ToString("#");
            }
            txtSumInsured.Text = _sumInsured.ToString();// dsApplication.Tables[2].Rows[0]["SumInsured"].ToString();
            txtInsurancePremium.Text = dsApplication.Tables[2].Rows[0]["Premium"].ToString();
            txtTotalPremium.Text = dsApplication.Tables[2].Rows[0]["TotalPremium"].ToString();
            txtCollectedAmount.Text = dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"].ToString();
            lblUpPremium.Text = dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"].ToString();
            txtCTPL.Text = dsApplication.Tables[2].Rows[0]["CTPL"].ToString();
            txtCurrentInsurer.Text = dsApplication.Tables[2].Rows[0]["CurrentInsurer"].ToString();

            if (dsApplication.Tables[2].Rows[0]["IsCTPL"].ToString() == "False" || dsApplication.Tables[2].Rows[0]["IsCTPL"].ToString() == "false" || dsApplication.Tables[2].Rows[0]["IsCTPL"].ToString() == "0")
            {
                ddlCTPL.Text = "0";
            }
            else
            {
                ddlCTPL.Text = "1";
            }

            txtInsuranceCompany.Text = dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();

            txtEngineNumber.Text = dsApplication.Tables[2].Rows[0]["EngineNumber"].ToString();
            txtChassisNumber.Text = dsApplication.Tables[2].Rows[0]["ChassisNumber"].ToString();
            txtPlateNumber.Text = dsApplication.Tables[2].Rows[0]["CarPlate"].ToString();
            txtRegistrationProvince.Text = dsApplication.Tables[2].Rows[0]["CarPlateProvince"].ToString();
            ddlNCB.Text = dsApplication.Tables[2].Rows[0]["NCB"].ToString();


            txtProviderId.Text = dsApplication.Tables[0].Rows[0]["CXBrokerProviderId"].ToString();
            LoadLableColor();
            txtNewQuoteRefNo.Text = dsApplication.Tables[2].Rows[0]["QuoteRefNo"].ToString();
            txtUserId.Text = dsApplication.Tables[2].Rows[0]["RefCEUserId"].ToString();

            ddlCustomerType.Text = dsApplication.Tables[2].Rows[0]["CustomerType"].ToString();
            txtCustomerName.Text = dsApplication.Tables[2].Rows[0]["CustomerName"].ToString();
            txtPrefix.Text = dsApplication.Tables[2].Rows[0]["Title"].ToString();
            txtBeneficiary.Text = dsApplication.Tables[2].Rows[0]["Beneficiary"].ToString();
            txtInsuredPerson.Text = dsApplication.Tables[2].Rows[0]["Name"].ToString();
            txtContactNumber.Text = dsApplication.Tables[2].Rows[0]["ContactNo"].ToString();
            if (dsApplication.Tables[2].Rows[0]["OfficePhoneNo"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["OfficePhoneNo"].ToString() != string.Empty)
            {
                txtOtherContactNumber.Text = dsApplication.Tables[2].Rows[0]["OfficePhoneNo"].ToString();
            }
            txtCitizenID.Text = "";
            if (dsApplication.Tables[2].Rows[0]["IdentificationNo"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["IdentificationNo"].ToString() != string.Empty)
            {
                txtCitizenID.Text = dsApplication.Tables[2].Rows[0]["IdentificationNo"].ToString();
            }
            txtCurrentAddress.Text = dsApplication.Tables[2].Rows[0]["PresentAddress"].ToString();
            txtSubDistrict.Text = dsApplication.Tables[2].Rows[0]["SubDistrict"].ToString();
            txtStateProvince.Text = dsApplication.Tables[2].Rows[0]["District"].ToString();
            txtProvince.Text = dsApplication.Tables[2].Rows[0]["Province"].ToString();
            txtPostalCode.Text = dsApplication.Tables[2].Rows[0]["PostalCode"].ToString();
            txtPackage.Text = dsApplication.Tables[2].Rows[0]["Package"].ToString();

            if (dsApplication.Tables[2].Rows[0]["Gender"] != DBNull.Value)
            {
                ddlGender.Text = dsApplication.Tables[2].Rows[0]["Gender"].ToString();
            }

            DateTime DOB = dateTimeNow; //DateTime.Now;
            if (dsApplication.Tables[2].Rows[0]["DOB"] != DBNull.Value && dsApplication.Tables[2].Rows[0]["DOB"].ToString() != string.Empty)
            {
                DOB = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["DOB"].ToString());
            }
            AssignDate(DOB.Day, ddlDOBDay);
            AssignMonth(DOB.Month, ddlDOBMonth);
            AssignYear(DOB.Year, ddlDOBYear);
            DateTime DriverDOB1 = dateTimeNow.AddYears(-20); //DateTime.Now.AddYears(-20)
            DateTime DriverDOB2 = dateTimeNow.AddYears(-20); //DateTime.Now.AddYears(-20)
            ddlOccupation.Text = dsApplication.Tables[2].Rows[0]["Occupation"].ToString();
            ddlNamedDriver.Text = dsApplication.Tables[2].Rows[0]["NoOfDriver"].ToString();
            ddlNamedDriver_SelectedIndexChanged(null, null);
            if (ddlNamedDriver.Text == "0")
            {
                txtDriverId1.Text = "0";
                txtDriverId2.Text = "0";
            }
            else if (ddlNamedDriver.Text == "1")
            {
                txtDriverId2.Text = "0";
            }
            if (dsApplication.Tables.Count > 3)
            {
                if (dsApplication.Tables[3].Rows.Count > 0 && dsApplication.Tables[3].Rows[0]["CarDriverId"] != DBNull.Value && dsApplication.Tables[3].Rows[0]["CarDriverId"].ToString() != string.Empty)
                {
                    txtDriverId1.Text = dsApplication.Tables[3].Rows[0]["CarDriverId"].ToString();
                }
                if (dsApplication.Tables[3].Rows.Count > 0 && dsApplication.Tables[3].Rows[0]["DOB"] != DBNull.Value && dsApplication.Tables[3].Rows[0]["DOB"].ToString() != string.Empty)
                {
                    DriverDOB1 = Convert.ToDateTime(dsApplication.Tables[3].Rows[0]["DOB"].ToString());
                }
                if (dsApplication.Tables[3].Rows.Count > 0 && dsApplication.Tables[3].Rows[1]["CarDriverId"] != DBNull.Value && dsApplication.Tables[3].Rows[1]["CarDriverId"].ToString() != string.Empty)
                {
                    txtDriverId2.Text = dsApplication.Tables[3].Rows[1]["CarDriverId"].ToString();
                }
                if (dsApplication.Tables[3].Rows.Count > 1 && dsApplication.Tables[3].Rows[1]["DOB"] != DBNull.Value && dsApplication.Tables[3].Rows[1]["DOB"].ToString() != string.Empty)
                {
                    DriverDOB2 = Convert.ToDateTime(dsApplication.Tables[3].Rows[1]["DOB"].ToString());
                }
                if (dsApplication.Tables[3].Rows.Count > 0)
                {
                    txtDriverFirst.Text = dsApplication.Tables[3].Rows[0]["FullName"].ToString();
                    txtDriver1IDNo.Text = dsApplication.Tables[3].Rows[0]["IDNo"].ToString();
                    txtDriver1LicenseNo.Text = dsApplication.Tables[3].Rows[0]["DrivingLicenseNumber"].ToString();
                    txtDriverId1.Text = dsApplication.Tables[3].Rows[0]["CarDriverId"].ToString();
                }
                if (dsApplication.Tables[3].Rows.Count > 1)
                {
                    txtDriverTwo.Text = dsApplication.Tables[3].Rows[1]["FullName"].ToString();
                    txtDriver2IDNo.Text = dsApplication.Tables[3].Rows[1]["IDNo"].ToString();
                    txtDriver2LicenseNo.Text = dsApplication.Tables[3].Rows[1]["DrivingLicenseNumber"].ToString();
                    txtDriverId2.Text = dsApplication.Tables[3].Rows[1]["CarDriverId"].ToString();
                }
            }
            AssignDate(DriverDOB1.Day, ddlDriver1DOBDay);
            AssignMonth(DriverDOB1.Month, ddlDriver1DOBMonth);
            AssignYear(DriverDOB1.Year, ddlDriver1DOBYear);
            AssignDate(DriverDOB2.Day, ddlDriver2DOBDay);
            AssignMonth(DriverDOB2.Month, ddlDriver2DOBMonth);
            AssignYear(DriverDOB2.Year, ddlDriver2DOBYear);

            DateTime _CreateDate = Convert.ToDateTime(dsApplication.Tables[2].Rows[0]["CreatedDate"].ToString());
            if (ddlApplicationDay.Items.Count > 0)
                ddlApplicationDay.Items.Clear();
            ddlApplicationDay.Items.Add(new ListItem(_CreateDate.Day.ToString("00"), _CreateDate.Day.ToString("00")));
            if (ddlApplicationMonth.Items.Count > 0)
                ddlApplicationMonth.Items.Clear();
            ddlApplicationMonth.Items.Add(new ListItem(_CreateDate.Month.ToString("00"), _CreateDate.Month.ToString("00")));
            if (ddlApplicationYear.Items.Count > 0)
                ddlApplicationYear.Items.Clear();
            ddlApplicationYear.Items.Add(new ListItem(_CreateDate.Year.ToString("0000"), _CreateDate.Year.ToString("0000")));

            if (ddlNamedDriver.Text == "0")
            {
                rfvDriverFirst.Enabled = false;
                revDriverFirst.Enabled = false;
                rfvDriver1IDNo.Enabled = false;
                rfvDriver1LicenseNo.Enabled = false;
                rfvDriverTwo.Enabled = false;
                revDriverTwo.Enabled = false;
                rfvDriver2IDNo.Enabled = false;
                rfvDriver2LicenseNo.Enabled = false;
            }
            if (ddlNamedDriver.Text == "1")
            {
                rfvDriverFirst.Enabled = true;
                revDriverFirst.Enabled = true;
                rfvDriver1IDNo.Enabled = true;
                rfvDriver1LicenseNo.Enabled = true;
                rfvDriverTwo.Enabled = false;
                revDriverTwo.Enabled = false;
                rfvDriver2IDNo.Enabled = false;
                rfvDriver2LicenseNo.Enabled = false;
            }
            if (ddlNamedDriver.Text == "2")
            {
                rfvDriverFirst.Enabled = true;
                revDriverFirst.Enabled = true;
                rfvDriver1IDNo.Enabled = true;
                rfvDriver1LicenseNo.Enabled = true;
                rfvDriverTwo.Enabled = true;
                revDriverTwo.Enabled = true;
                rfvDriver2IDNo.Enabled = true;
                rfvDriver2LicenseNo.Enabled = true;
            }

            pnlCarDetails.Visible = true;
            #endregion

        }
        else
        {
            lblSearchMessage.Text = Resources.General.CheckRefNo;
            divCar.Visible = false;
        }

    }

    public void LoadLastYearApplicationDetails()
    {
        if (lblLastYearRefNo.Text != string.Empty)
        {
            DataSet _dsLastYearApplication = new DataSet();
            NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
            _dsLastYearApplication = _nonggpackagedb.GetLastYearCarDetails(Convert.ToInt64(txtCarId.Text.Trim()), lblLastYearRefNo.Text.ToUpper());
            if (_dsLastYearApplication != null && _dsLastYearApplication.Tables.Count > 0 && _dsLastYearApplication.Tables[0].Rows.Count > 0)
            {

                txtCarModelYear.Text = _dsLastYearApplication.Tables[0].Rows[0]["CarYear"].ToString();
                txtCarMakeModel.Text = _dsLastYearApplication.Tables[0].Rows[0]["CarModel"].ToString();

                txtCurrentInsurer.Text = _dsLastYearApplication.Tables[0].Rows[0]["CompanyName"].ToString();

                txtEngineNumber.Text = _dsLastYearApplication.Tables[0].Rows[0]["EngineNumber"].ToString();
                txtChassisNumber.Text = _dsLastYearApplication.Tables[0].Rows[0]["ChassisNumber"].ToString();
                txtPlateNumber.Text = _dsLastYearApplication.Tables[0].Rows[0]["CarPlate"].ToString();
                txtRegistrationProvince.Text = _dsLastYearApplication.Tables[0].Rows[0]["CarPlateProvince"].ToString();
                ddlNCB.Text = _dsLastYearApplication.Tables[0].Rows[0]["NCB"].ToString();

                txtUserId.Text = _dsLastYearApplication.Tables[0].Rows[0]["RefCEUserId"].ToString();

                lblUpApplicantName.Text = _dsLastYearApplication.Tables[0].Rows[0]["Name"].ToString();
                lblUpPlanName.Text = _dsLastYearApplication.Tables[0].Rows[0]["Package"].ToString();
                txtCancelStatus.Text = "0";

                ddlCustomerType.Text = _dsLastYearApplication.Tables[0].Rows[0]["CustomerType"].ToString();
                txtCustomerName.Text = _dsLastYearApplication.Tables[0].Rows[0]["CustomerName"].ToString();
                txtPrefix.Text = _dsLastYearApplication.Tables[0].Rows[0]["Title"].ToString();
                txtBeneficiary.Text = _dsLastYearApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
                txtInsuredPerson.Text = _dsLastYearApplication.Tables[0].Rows[0]["Name"].ToString();
                txtContactNumber.Text = _dsLastYearApplication.Tables[0].Rows[0]["ContactNo"].ToString();
                txtCurrentAddress.Text = _dsLastYearApplication.Tables[0].Rows[0]["PresentAddress"].ToString();
                txtSubDistrict.Text = _dsLastYearApplication.Tables[0].Rows[0]["SubDistrict"].ToString();
                txtStateProvince.Text = _dsLastYearApplication.Tables[0].Rows[0]["District"].ToString();
                txtProvince.Text = _dsLastYearApplication.Tables[0].Rows[0]["Province"].ToString();
                txtPostalCode.Text = _dsLastYearApplication.Tables[0].Rows[0]["PostalCode"].ToString();
                txtPackage.Text = _dsLastYearApplication.Tables[0].Rows[0]["Package"].ToString();

                if (_dsLastYearApplication.Tables[0].Rows[0]["Gender"] != DBNull.Value)
                {
                    ddlGender.Text = _dsLastYearApplication.Tables[0].Rows[0]["Gender"].ToString();
                }

                DateTime DOB = dateTimeNow; //DateTime.Now;
                if (_dsLastYearApplication.Tables[0].Rows[0]["DOB"] != DBNull.Value && _dsLastYearApplication.Tables[0].Rows[0]["DOB"].ToString() != string.Empty)
                {
                    DOB = Convert.ToDateTime(_dsLastYearApplication.Tables[0].Rows[0]["DOB"].ToString());
                }
                AssignDate(DOB.Day, ddlDOBDay);
                AssignMonth(DOB.Month, ddlDOBMonth);
                AssignYear(DOB.Year, ddlDOBYear);
                DateTime DriverDOB1 = dateTimeNow.AddYears(-20); //DateTime.Now.AddYears(-20);
                DateTime DriverDOB2 = dateTimeNow.AddYears(-20); //DateTime.Now.AddYears(-20);
                ddlOccupation.Text = _dsLastYearApplication.Tables[0].Rows[0]["Occupation"].ToString();
                ddlNamedDriver.Text = _dsLastYearApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
                ddlNamedDriver_SelectedIndexChanged(null, null);
                txtDriverId1.Text = "0";
                txtDriverId2.Text = "0";
                if (_dsLastYearApplication.Tables.Count > 1 && ddlNamedDriver.Text != "0")
                {
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 0 && _dsLastYearApplication.Tables[1].Rows[0]["CarDriverId"] != DBNull.Value && _dsLastYearApplication.Tables[1].Rows[0]["CarDriverId"].ToString() != string.Empty)
                    {
                        txtDriverId1.Text = _dsLastYearApplication.Tables[1].Rows[0]["CarDriverId"].ToString();
                    }
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 0 && _dsLastYearApplication.Tables[1].Rows[0]["DOB"] != DBNull.Value && _dsLastYearApplication.Tables[1].Rows[0]["DOB"].ToString() != string.Empty)
                    {
                        DriverDOB1 = Convert.ToDateTime(_dsLastYearApplication.Tables[1].Rows[0]["DOB"].ToString());
                    }
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 0 && _dsLastYearApplication.Tables[1].Rows[1]["CarDriverId"] != DBNull.Value && _dsLastYearApplication.Tables[1].Rows[1]["CarDriverId"].ToString() != string.Empty)
                    {
                        txtDriverId2.Text = _dsLastYearApplication.Tables[1].Rows[1]["CarDriverId"].ToString();
                    }
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 1 && _dsLastYearApplication.Tables[1].Rows[1]["DOB"] != DBNull.Value && _dsLastYearApplication.Tables[1].Rows[1]["DOB"].ToString() != string.Empty)
                    {
                        DriverDOB2 = Convert.ToDateTime(_dsLastYearApplication.Tables[1].Rows[1]["DOB"].ToString());
                    }
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 0)
                    {
                        txtDriverFirst.Text = _dsLastYearApplication.Tables[1].Rows[0]["FullName"].ToString();
                        txtDriver1IDNo.Text = _dsLastYearApplication.Tables[1].Rows[0]["IDNo"].ToString();
                        txtDriver1LicenseNo.Text = _dsLastYearApplication.Tables[1].Rows[0]["DrivingLicenseNumber"].ToString();
                    }
                    if (_dsLastYearApplication.Tables[1].Rows.Count > 1)
                    {
                        txtDriverTwo.Text = _dsLastYearApplication.Tables[1].Rows[1]["FullName"].ToString();
                        txtDriver2IDNo.Text = _dsLastYearApplication.Tables[1].Rows[1]["IDNo"].ToString();
                        txtDriver2LicenseNo.Text = _dsLastYearApplication.Tables[1].Rows[1]["DrivingLicenseNumber"].ToString();
                    }
                }
                AssignDate(DriverDOB1.Day, ddlDriver1DOBDay);
                AssignMonth(DriverDOB1.Month, ddlDriver1DOBMonth);
                AssignYear(DriverDOB1.Year, ddlDriver1DOBYear);
                AssignDate(DriverDOB2.Day, ddlDriver2DOBDay);
                AssignMonth(DriverDOB2.Month, ddlDriver2DOBMonth);
                AssignYear(DriverDOB2.Year, ddlDriver2DOBYear);

                DateTime _CreateDate = Convert.ToDateTime(_dsLastYearApplication.Tables[0].Rows[0]["CreatedDate"].ToString());
                if (ddlApplicationDay.Items.Count > 0)
                    ddlApplicationDay.Items.Clear();
                ddlApplicationDay.Items.Add(new ListItem(_CreateDate.Day.ToString("00"), _CreateDate.Day.ToString("00")));
                if (ddlApplicationMonth.Items.Count > 0)
                    ddlApplicationMonth.Items.Clear();
                ddlApplicationMonth.Items.Add(new ListItem(_CreateDate.Month.ToString("00"), _CreateDate.Month.ToString("00")));
                if (ddlApplicationYear.Items.Count > 0)
                    ddlApplicationYear.Items.Clear();
                ddlApplicationYear.Items.Add(new ListItem(_CreateDate.Year.ToString("0000"), _CreateDate.Year.ToString("0000")));

                if (ddlNamedDriver.Text == "0")
                {
                    rfvDriverFirst.Enabled = false;
                    revDriverFirst.Enabled = false;
                    rfvDriver1IDNo.Enabled = false;
                    rfvDriver1LicenseNo.Enabled = false;
                    rfvDriverTwo.Enabled = false;
                    revDriverTwo.Enabled = false;
                    rfvDriver2IDNo.Enabled = false;
                    rfvDriver2LicenseNo.Enabled = false;
                }
                if (ddlNamedDriver.Text == "1")
                {
                    rfvDriverFirst.Enabled = true;
                    revDriverFirst.Enabled = true;
                    rfvDriver1IDNo.Enabled = true;
                    rfvDriver1LicenseNo.Enabled = true;
                    rfvDriverTwo.Enabled = false;
                    revDriverTwo.Enabled = false;
                    rfvDriver2IDNo.Enabled = false;
                    rfvDriver2LicenseNo.Enabled = false;
                }
                if (ddlNamedDriver.Text == "2")
                {
                    rfvDriverFirst.Enabled = true;
                    revDriverFirst.Enabled = true;
                    rfvDriver1IDNo.Enabled = true;
                    rfvDriver1LicenseNo.Enabled = true;
                    rfvDriverTwo.Enabled = true;
                    revDriverTwo.Enabled = true;
                    rfvDriver2IDNo.Enabled = true;
                    rfvDriver2LicenseNo.Enabled = true;
                }
            }
        }
    }

    public void GetCarMoreDetails()
    {
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        string _spName = "sprocMerchantCarMoreDetailSelectSingleItem";
        SortedList _spara = new SortedList();
        _spara.Add("@CarId", Convert.ToInt64(txtCarId.Text.Trim()));
        _spara.Add("@RefCEUserId", Convert.ToInt64(txtCEId.Text));
        DataSet _dsCarMoreDetails = new DataSet();
        _dsCarMoreDetails = _db.GetDataSet(_spName, _spara);
        if (_dsCarMoreDetails != null && _dsCarMoreDetails.Tables.Count > 0 && _dsCarMoreDetails.Tables[1].Rows.Count > 0)
        {
            lblPRefNo.Text = _dsCarMoreDetails.Tables[1].Rows[0]["QuoteRefNo"].ToString();
            lblUpRefNo.Text = _dsCarMoreDetails.Tables[1].Rows[0]["QuoteRefNo"].ToString();
            lblUpApplicantName.Text = _dsCarMoreDetails.Tables[1].Rows[0]["Name"].ToString();
            lblUpInsurer.Text = _dsCarMoreDetails.Tables[1].Rows[0]["CompanyName"].ToString();
            lblUpPlanName.Text = _dsCarMoreDetails.Tables[1].Rows[0]["Package"].ToString();
            txtCancelStatus.Text = "0";
            if (_dsCarMoreDetails.Tables[0].Rows[0]["CancelStatus"] != DBNull.Value && _dsCarMoreDetails.Tables[0].Rows[0]["CancelStatus"].ToString() != "")
            {
                txtCancelStatus.Text = _dsCarMoreDetails.Tables[0].Rows[0]["CancelStatus"].ToString();
            }
            if (txtCancelStatus.Text == "1")
            {
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Retrieve, "RTRV"));
                ddlOption.SelectedIndex = 0;
            }
            else
            {
                LoadOption();
            }

            if (_dsCarMoreDetails.Tables.Count > 1 && _dsCarMoreDetails.Tables[1].Rows.Count > 0)
            {

                lblUpPremium.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWOD"].ToString();

                lblUpPremium.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremium"].ToString();


                lblUpPremiumWD.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWD"].ToString();
                lblUpPremiumWOD.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWOD"].ToString();
                lblUpPaymentType.Text = _dsCarMoreDetails.Tables[1].Rows[0]["PaymentType"].ToString();
                lblUpPaymentStatus.Text = _dsCarMoreDetails.Tables[1].Rows[0]["PaymentStatus"].ToString();

                txtWDPremium.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWD"].ToString();
                txtWODPremium.Text = _dsCarMoreDetails.Tables[1].Rows[0]["TotalCollectedPremiumWOD"].ToString();
                if (txtIsWD.Text != string.Empty && txtIsWD.Text == "0")
                {
                    txtAgentPrice.Text = txtWODPremium.Text;
                }
                else
                {
                    txtAgentPrice.Text = txtWDPremium.Text;
                }
                if (_dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWD"] != DBNull.Value &&
                    _dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWD"].ToString() != string.Empty)
                {
                    decimal _dOriginalPremiumWD = 0;
                    if (!decimal.TryParse(_dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWD"].ToString(), out _dOriginalPremiumWD))
                    {
                        _dOriginalPremiumWD = 0;
                    }
                    txtOriginalPriceWD.Text = _dOriginalPremiumWD.ToString("#0.00");
                }
                if (_dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWOD"] != DBNull.Value &&
                    _dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWOD"].ToString() != string.Empty)
                {
                    decimal _dOriginalPremiumWOD = 0;
                    if (!decimal.TryParse(_dsCarMoreDetails.Tables[1].Rows[0]["OriginalPremiumWOD"].ToString(), out _dOriginalPremiumWOD))
                    {
                        _dOriginalPremiumWOD = 0;
                    }
                    txtOriginalPriceWOD.Text = _dOriginalPremiumWOD.ToString("#0.00");
                }
                if (_dsCarMoreDetails.Tables[1].Rows[0]["ApprovedPremium"] != DBNull.Value &&
                    _dsCarMoreDetails.Tables[1].Rows[0]["ApprovedPremium"].ToString() != string.Empty)
                {
                    decimal _dApprovedPremium = 0;
                    if (!decimal.TryParse(_dsCarMoreDetails.Tables[1].Rows[0]["ApprovedPremium"].ToString(), out _dApprovedPremium))
                    {
                        _dApprovedPremium = 0;
                    }

                }
            }
            if (ddlOption.Items.Count > 0)
            {
                ddlOption_SelectedIndexChanged(null, null);
            }
        }
        else
        {
            DataSet _dsCarDetails = new DataSet();
            _dsCarDetails = GetBrokerPremium();
            if (_dsCarDetails != null && _dsCarDetails.Tables.Count > 0 && _dsCarDetails.Tables[0].Rows.Count > 0)
            {
                txtAgentComments.Text = "";
                if (_dsCarDetails.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsCarDetails.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                {
                    txtAgentComments.Text = _dsCarDetails.Tables[0].Rows[0]["Info8"].ToString();
                }
                pnlDetails.Visible = true;
                lblPRefNo.Text = _dsCarDetails.Tables[0].Rows[0]["Info1"].ToString();
                lblUpRefNo.Text = _dsCarDetails.Tables[0].Rows[0]["Info1"].ToString();
                if (_dsCarDetails.Tables[0].Rows[0]["Info4"] != DBNull.Value && _dsCarDetails.Tables[0].Rows[0]["Info4"].ToString() == "1")
                {
                    lblCompanyStaff.Text = "1";
                    if (Session[General.UserRole].ToString() == "100")
                    {
                        lblOptionError.Text = Resources.Proposal.AccessDenied;
                        btnSubmit.Enabled = false;
                    }
                }
                else
                {
                    lblCompanyStaff.Text = "0";
                }

                lblUpInsurer.Text = CE.Global.General.GetProviderName(Convert.ToInt64(txtProviderId.Text), lblLangOption.Text);
                lblUpPlanName.Text = _dsCarDetails.Tables[0].Rows[0]["Package"].ToString();
                lblUpPremiumWD.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWD"].ToString();
                lblUpPremiumWOD.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWOD"].ToString();


                lblUpPremium.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWOD"].ToString();

                lblUpPremium.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmount"].ToString();


                txtWDPremium.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWD"].ToString();
                txtAFTPremiumWOD.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumTescoCashWOD"].ToString();
                txtAFTPremiumWD.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumTescoCashWD"].ToString();
                txtWODPremium.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWOD"].ToString();
                if (txtIsWD.Text != string.Empty && txtIsWD.Text == "0")
                {
                    txtAgentPrice.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWOD"].ToString();
                }
                else
                {
                    txtAgentPrice.Text = _dsCarDetails.Tables[0].Rows[0]["PremiumAmountWD"].ToString();
                }
                if (_dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWD"] != DBNull.Value &&
                    _dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWD"].ToString() != string.Empty)
                {
                    decimal _dOriginalPremiumWD = 0;
                    if (!decimal.TryParse(_dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWD"].ToString(), out _dOriginalPremiumWD))
                    {
                        _dOriginalPremiumWD = 0;
                    }
                    txtOriginalPriceWD.Text = _dOriginalPremiumWD.ToString("#0.00");
                }
                if (_dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWOD"] != DBNull.Value &&
                    _dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWOD"].ToString() != string.Empty)
                {
                    decimal _dOriginalPremiumWOD = 0;
                    if (!decimal.TryParse(_dsCarDetails.Tables[0].Rows[0]["OriginalPremiumWOD"].ToString(), out _dOriginalPremiumWOD))
                    {
                        _dOriginalPremiumWOD = 0;
                    }
                    txtOriginalPriceWOD.Text = _dOriginalPremiumWOD.ToString("#0.00");
                }
                if (_dsCarDetails.Tables[0].Rows[0]["ApprovedPremium"] != DBNull.Value &&
                    _dsCarDetails.Tables[0].Rows[0]["ApprovedPremium"].ToString() != string.Empty)
                {
                    decimal _dApprovedPremium = 0;
                    if (!decimal.TryParse(_dsCarDetails.Tables[0].Rows[0]["ApprovedPremium"].ToString(), out _dApprovedPremium))
                    {
                        _dApprovedPremium = 0;
                    }
                }

                lblUpPaymentStatus.Text = "PENDING";
                if (_dsCarDetails != null && _dsCarDetails.Tables.Count > 1 && _dsCarDetails.Tables[1].Rows.Count > 0)
                {
                    lblUpPaymentStatus.Text = "PENDING";
                }
            }
        }

        if (_dsCarMoreDetails != null && _dsCarMoreDetails.Tables.Count > 0 && _dsCarMoreDetails.Tables[0].Rows.Count > 0)
        {
            if (_dsCarMoreDetails.Tables[0].Rows[0]["Mailing"] != DBNull.Value && _dsCarMoreDetails.Tables[0].Rows[0]["Mailing"].ToString() != string.Empty)
            {
                if (_dsCarMoreDetails.Tables[0].Rows[0]["Mailing"].ToString() == "1")
                {
                    ddlOption.Items.Clear();
                    ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                    ddlOption.Items.Add(new ListItem(Resources.CarInsurance.UploadFile, "UPLD"));
                    ddlOption.SelectedIndex = 0;
                }
            }
        }
    }

    public DataSet GetBrokerPremium()
    {
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocMerchantBrokerPremiumSelectSingleItem";
        _sPara.Add("@CXBrokerProviderId", Convert.ToInt64(txtProviderId.Text));
        _sPara.Add("@CarId", Convert.ToInt64(txtCarId.Text.Trim()));
        _sPara.Add("@SelectedStatus", true);
        DataSet _ds = new DataSet();
        return _ds = _db.GetDataSet(_spName, _sPara);
        lblLoadMessage.Text = string.Empty;
    }

    public DataSet GetPaymentAmounts()
    {
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocMerchantPaymentsAmountsSelectItembyQuoteRefNo";
        _sPara.Add("@QuoteRefNo", lblUpRefNo.Text);
        DataSet _ds = new DataSet();
        return _ds = _db.GetDataSet(_spName, _sPara);
        lblLoadMessage.Text = string.Empty;
    }

    public DataSet GetApprovedPayments()
    {
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocMerchantApprovedPaymentSelectItemList";
        _sPara.Add("@ProviderCompanyId", Convert.ToInt64(txtProviderId.Text));
        _sPara.Add("@CarId", Convert.ToInt64(txtCarId.Text.Trim()));
        DataSet _ds = new DataSet();
        return _ds = _db.GetDataSet(_spName, _sPara);
        lblLoadMessage.Text = string.Empty;
    }

    public bool CheckSelectedItem(string QouteRefNo)
    {
        bool _Result = false;
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocMerchantPremiumSelectItemByQuoteRefNo";
        _sPara.Add("@QouteRefNo", QouteRefNo);
        DataSet _ds = new DataSet();
        _ds = _db.GetDataSet(_spName, _sPara);
        if (_ds != null && _ds.Tables.Count > 0 && _ds.Tables[0].Rows.Count > 0)
        {
            _Result = true;
        }
        return _Result;
    }

    public bool CheckApplicationProcessStatus(string QouteRefNo, string Process)
    {
        bool _Result = true;
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocMerchantApplicationSelectItemByQuoteRefNo";
        _sPara.Add("@QuoteRefNo", QouteRefNo);
        DataSet _ds = new DataSet();
        _ds = _db.GetDataSet(_spName, _sPara);
        if (_ds != null && _ds.Tables.Count > 0 && _ds.Tables[0].Rows.Count > 0)
        {
            string _status = "";
            if (Process.ToUpper() == "MAILING")
            {
                if (_ds.Tables[0].Rows[0]["Mailing"].ToString() != null && _ds.Tables[0].Rows[0]["Mailing"].ToString() != string.Empty)
                {
                    _status = _ds.Tables[0].Rows[0]["Mailing"].ToString();
                    if (_status != string.Empty && _status == "1")
                    {
                        _Result = false;
                    }
                }
            }
        }
        return _Result;
    }

    private bool GetBoolean(Int16 val)
    {
        bool _result = false;
        if (val == 1)
        {
            _result = true;
        }
        return _result;
    }

    private void AssignDate(Int32 _date, DropDownList ddl)
    {
        string val = _date.ToString();
        if (_date < 10)
        {
            val = "0" + _date.ToString();
        }

        ddl.Text = val;
    }

    private void AssignMonth(Int32 _month, DropDownList ddl)
    {
        string val = "00";
        string monthname = Resources.General.Select;
        if (_month < 10)
        {
            val = "0" + _month.ToString();
        }
        else
        {
            val = _month.ToString();
        }

        ddl.Text = val;
    }

    private void AssignYear(Int32 _year, DropDownList ddl)
    {
        if (_year > (dateTimeNow.Year + 400)) //DateTime.Now.Year
        {
            _year = _year - 543;
        }
        string val = _year.ToString();

        ddl.Text = val;
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Page.Validate("fleet");

        if (lblCompanyStaff.Text == "1" && Session[General.UserRole].ToString() == "100")
        {
            lblOptionError.Text = Resources.Proposal.AccessDenied;
            return;
        }

        if (Page.IsValid)
        {
            lblLoadMessage.Text = string.Empty;
            Int64 _result = -1;
            Int64 _AgentId = 0;
            Int64 _AdminId = 0;
            if (!Int64.TryParse(lblAgentId.Text, out _AgentId))
            {
                _AgentId = 0;
            }
            if (!Int64.TryParse(lblAdminId.Text, out _AdminId))
            {
                _AdminId = 0;
            }
            txtLastQuoteRefNo.Text = txtSearch.Text.Trim();
            MerchantPackage _merchantpackage = new MerchantPackage();
            MerchantPackageDB _merchantpackagedb = new MerchantPackageDB();
            _merchantpackage.CarId = Convert.ToInt64(txtCarId.Text);
            _merchantpackage.RefCEUserId = Convert.ToInt64(txtCEId.Text);
            _merchantpackage.MerchantId = Convert.ToInt64(txtMerchantId.Text);
            _merchantpackage.ProviderCompanyId = Convert.ToInt64(txtProviderId.Text);
            _merchantpackage.Title = Server.HtmlEncode(txtPrefix.Text);
            _merchantpackage.CustomerType = ddlCustomerType.Text;
            _merchantpackage.CustomerName = Server.HtmlEncode(txtCustomerName.Text);
            _merchantpackage.Name = Server.HtmlEncode(txtInsuredPerson.Text);
            DateTime _dtDOB = new DateTime(Convert.ToInt32(ddlDOBYear.Text), Convert.ToInt32(ddlDOBMonth.Text), Convert.ToInt32(ddlDOBDay.Text));
            _merchantpackage.DOB = _dtDOB;
            _merchantpackage.Gender = ddlGender.Text;
            _merchantpackage.Occupation = Convert.ToInt32(ddlOccupation.Text);
            _merchantpackage.ContactNo = Server.HtmlEncode(txtContactNumber.Text);
            _merchantpackage.OfficePhoneNo = Server.HtmlEncode(txtOtherContactNumber.Text);
            _merchantpackage.IdentificationNo = Server.HtmlEncode(txtCitizenID.Text);
            _merchantpackage.PresentAddress = Server.HtmlEncode(txtCurrentAddress.Text);
            _merchantpackage.SubDistrict = Server.HtmlEncode(txtSubDistrict.Text);
            _merchantpackage.District = Server.HtmlEncode(txtStateProvince.Text);
            _merchantpackage.Province = Server.HtmlEncode(txtProvince.Text);
            _merchantpackage.PostalCode = txtPostalCode.Text;
            _merchantpackage.Package = Server.HtmlEncode(txtPackage.Text);
            _merchantpackage.NoOfDriver = Convert.ToInt16(ddlNamedDriver.Text);
            _merchantpackage.InsuranceType = Convert.ToInt32(ddlInsuranceType.Text);
            _merchantpackage.GarageType = Convert.ToInt32(ddlGarageType.Text);
            _merchantpackage.CarYear = Convert.ToInt32(txtCarModelYear.Text);
            _merchantpackage.CarModel = Server.HtmlEncode(txtCarMakeModel.Text);

            _merchantpackage.Beneficiary = Server.HtmlEncode(txtBeneficiary.Text);
            _merchantpackage.VehicleType = Convert.ToInt32(ddlVehicleType.Text);

            Int32 _outSumInsurred = 0;
            if (!Int32.TryParse(txtSumInsured.Text, out _outSumInsurred))
            {
                _outSumInsurred = 0;
            }
            _merchantpackage.SumInsured = _outSumInsurred;
            _merchantpackage.NCB = Convert.ToInt32(ddlNCB.Text);
            _merchantpackage.CurrentInsurer = Server.HtmlEncode(txtCurrentInsurer.Text);
            _merchantpackage.CarPlate = Server.HtmlEncode(txtPlateNumber.Text);
            _merchantpackage.CarPlateProvince = Server.HtmlEncode(txtRegistrationProvince.Text);
            _merchantpackage.EngineNumber = Server.HtmlEncode(txtEngineNumber.Text);
            _merchantpackage.ChassisNumber = Server.HtmlEncode(txtChassisNumber.Text);

            DateTime _dtCommDate = new DateTime(Convert.ToInt32(ddlCommenceYear.Text), Convert.ToInt32(ddlCommenceMonth.Text), Convert.ToInt32(ddlCommenceDay.Text));
            _merchantpackage.CoverageStart = _dtCommDate;
            DateTime _dtPolicyDate = new DateTime(Convert.ToInt32(ddlPolicyYear.Text), Convert.ToInt32(ddlPolicyMonth.Text), Convert.ToInt32(ddlPolicyDay.Text));
            _merchantpackage.CTPLStart = _dtPolicyDate;

            _merchantpackage.Premium = Convert.ToSingle(txtInsurancePremium.Text);
            _merchantpackage.IsCTPL = GetBoolean(Convert.ToInt16(ddlCTPL.Text));
            _merchantpackage.CTPL = Convert.ToSingle(txtCTPL.Text);

            _merchantpackage.TotalCollectedPremium = Convert.ToSingle(txtCollectedAmount.Text);
            _merchantpackage.TotalPremium = Convert.ToSingle(txtTotalPremium.Text);
            _merchantpackage.TermPremium = Convert.ToSingle(txtTotalPremium.Text);
            //_merchantpackage.PaymentStatus = false;
            _merchantpackage.QuoteRefNo = txtNewQuoteRefNo.Text;
            _merchantpackage.Status = true;
            //_merchantpackage.RefCEUserId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
            if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "100")
            {
                _merchantpackage.AgentId = Convert.ToInt64(txtAgentId.Text.Trim());
                _merchantpackage.AdminId = _AdminId;
            }
            else
            {
                _merchantpackage.AgentId = Convert.ToInt64(txtAgentId.Text.Trim());
                _merchantpackage.AdminId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
            }
            _merchantpackage.Info1 = ddlApplicationType.Text;
            if (ddlApplicationType.Text == "REN" || ddlApplicationType.Text == "CHB")
            {
                _merchantpackage.Info2 = txtLastYearPolicyNo.Text.Trim();
            }
            if (_merchantpackage.ProviderCompanyId == 43)
            {
                _merchantpackage.Info3 = txtInsurerEmail.Text.Trim();
            }
            if (chkIsCreditCardOwner.Checked)
            {
                _merchantpackage.IsCreditCardOwner = 1;
            }
            if (chkPromotion.Checked)
            {
                _merchantpackage.PromotionCode = "1";
            }
            if (trModificationAmount.Visible == true)
            {
                _merchantpackage.Info4 = Server.HtmlEncode(txtModificationAmount.Text.Trim());
            }
            _merchantpackage.Info8 = Server.HtmlEncode(txtAgentRemarkDetails.Text);
            _result = _merchantpackagedb.Insert(_merchantpackage);
            Int32 driverresult = 0;
            if (_result > 0)
            {
                if (Convert.ToInt16(ddlNamedDriver.Text) > 0)
                {
                    if (SaveDriverDetails())
                    {
                        driverresult = 1;
                        pnlCarDetails.Visible = false;
                        lblOptionMessage.Text = Resources.CarInsurance.SuccessfullySaved;
                        pnlOptionMessage.Visible = true;
                        pnlDetails.Visible = true;
                        divCar.Visible = true;
                    }
                    else
                    {
                        driverresult = 0;
                    }
                }
                else
                {
                    driverresult = 1;
                }
                if (driverresult > 0)
                {
                    string _fileName = lblUpRefNo.Text.Trim() + "_" + dateTimeNow.Day.ToString("00") + "-" + dateTimeNow.Month.ToString("00") + "-" + dateTimeNow.Year; //DateTime.Now.Day.ToString("00") + "-" + DateTime.Now.Month.ToString("00") + "-" + DateTime.Now.Year;
                    string _filePath = GetExcelFilePath(txtCEId.Text.Trim(), lblUpRefNo.Text.Trim());
                    string ExcelFile = GenerateMerchantExcel(_merchantpackage.CarId, _merchantpackage.ProviderCompanyId, _filePath, _fileName);
                    if (ExcelFile != null)
                    {
                        Int64 _excelResult = -1;
                        _excelResult = _merchantpackagedb.UpdateExcelName(_merchantpackage.CarId, ExcelFile);
                        if (_excelResult > 0)
                        {
                            string mailBody = "";
                            string _emailTitle = "";
                            string _toemail = "";
                            string _ccemail = "";
                            string _bccemail = "";
                            _emailTitle = "[" + lblUpRefNo.Text + "] ส่งงานประกันรถ คุณ [" + _merchantpackage.Name + "] [" + _merchantpackage.CarPlate + "]";
                            if (ddlApplicationType.Text == "NEW")
                            {
                                mailBody += Resources.Proposal.ApplicationType + " : " + Resources.Proposal.AppTypeNew + "<br/><br/>";
                            }
                            else if (ddlApplicationType.Text == "REN")
                            {
                                mailBody += Resources.Proposal.ApplicationType + " : " + Resources.Proposal.AppTypeRenewalSameInsurer + "<br/><br/>";
                            }
                            else if (ddlApplicationType.Text == "RNO")
                            {
                                mailBody += Resources.Proposal.ApplicationType + " : " + Resources.Proposal.AppTypeRenewalOtherInsurer + "<br/><br/>";
                            }
                            else if (ddlApplicationType.Text == "CHB")
                            {
                                mailBody += Resources.Proposal.ApplicationType + " : " + Resources.Proposal.AppTypeChangeBroker + "<br/><br/>";
                            }
                            mailBody += Resources.General.CustomerName + " : " + _merchantpackage.Name + "<br/><br/>";
                            mailBody += Resources.General.InsuranceCompany + " : " + txtInsuranceCompany.Text.Trim() + "<br/><br/>";
                            mailBody += Resources.General.InsuranceType + " : " + ddlInsuranceType.SelectedItem.Text + "<br/><br/>";
                            mailBody += Resources.NonGG.GarageType + " : " + ddlGarageType.SelectedItem.Text + "<br/><br/>";
                            mailBody += Resources.General.TotalCollectedAmount + " : " + txtCollectedAmount.Text.Trim() + "<br/><br/>";
                            string URL = ConfigurationManager.AppSettings["TH.BKKPaymentPage"].ToString(); //http://www.gluaygluay.com/payment/
                            mailBody += Resources.General.PaymentLink + " : " + URL + "?ref=" + lblUpRefNo.Text.Trim() + "<br/><br/>";
                            mailBody += Resources.General.Broker + " : " + Session[CE.Global.General.UserName].ToString() + "<br/><br/>";
                            _toemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");

                            _ccemail = "";//Session[CE.Global.General.UserEmail].ToString();
                            _bccemail = "";
                            if (Session[General.UserRole].ToString() == "100")
                            {
                                _ccemail += Session[General.SMTPReplyTo].ToString();
                            }

                            bool _mailSendingStatus = false;

                            _mailSendingStatus = MyMailManager.SendGGMail(ConfigurationManager.AppSettings["GGFormsSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGFormsSMTPAuthCode"].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString());

                            pnlCarDetails.Visible = false;
                            lblOptionMessage.Text = Resources.CarInsurance.SuccessfullySaved;
                            pnlOptionMessage.Visible = true;
                            divCar.Visible = true;

                            if (!_mailSendingStatus)
                            {
                                lblOptionMessage.Text += ". Email notification was FAILED.";
                            }
                            ddlOption.SelectedIndex = 0;
                            ddlOption_SelectedIndexChanged(null, null);

                        }
                    }
                }
            }
        }
        else
        {
            lblOptionError.Text = "Error."; // Resources.CarInsurance.SuccessfullySaved;
            pnlOptionMessage.Visible = true;
        }
    }

    protected void ddlApplicationType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlApplicationType.Text == "NEW")
        {
            lblLastYearPolicyNoTitle.Text = string.Empty;
            rfvLastYearPolicyNo.Enabled = false;
            txtLastYearPolicyNo.Visible = false;
            txtLastYearPolicyNo.Text = "";
            txtLastYearPolicyNo.Enabled = true;
        }
        else if (ddlApplicationType.Text == "REN")
        {
            lblLastYearPolicyNoTitle.Text = Resources.Proposal.LastYearPolicyNo;
            rfvLastYearPolicyNo.Enabled = true;
            txtLastYearPolicyNo.Visible = true;
            txtLastYearPolicyNo.Text = lblLastYearPolicyNo.Text;
            txtLastYearPolicyNo.Enabled = false;
        }
        else if (ddlApplicationType.Text == "RNO")
        {
            lblLastYearPolicyNoTitle.Text = string.Empty;
            rfvLastYearPolicyNo.Enabled = false;
            txtLastYearPolicyNo.Visible = false;
            txtLastYearPolicyNo.Text = "";
            txtLastYearPolicyNo.Enabled = true;
        }
        else if (ddlApplicationType.Text == "CHB")
        {
            lblLastYearPolicyNoTitle.Text = Resources.Proposal.LastYearPolicyNo;
            rfvLastYearPolicyNo.Enabled = true;
            txtLastYearPolicyNo.Visible = true;
            txtLastYearPolicyNo.Text = "";
            txtLastYearPolicyNo.Enabled = true;
            if (lblNonGGStatus.Text == "1")
            {
                txtLastYearPolicyNo.Text = lblLastYearPolicyNo.Text;
            }
        }
    }

    protected void ddlCTPL_SelectedIndexChanged(object sender, EventArgs e)
    {
        float TotalPremium = Convert.ToSingle(txtInsurancePremium.Text);
        if (ddlCTPL.Text == "1")
        {
            TotalPremium = Convert.ToSingle(txtInsurancePremium.Text) + Convert.ToSingle(txtCTPL.Text);
        }
        txtTotalPremium.Text = TotalPremium.ToString("#0.00");
    }

    protected void ddlNamedDriver_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (Convert.ToInt16(ddlNamedDriver.Text) == 0)
        {
            rfvDriverFirst.Enabled = false;
            revDriverFirst.Enabled = false;
            rfvDriver1IDNo.Enabled = false;
            rfvDriver1LicenseNo.Enabled = false;
            rfvDriverTwo.Enabled = false;
            revDriverTwo.Enabled = false;
            rfvDriver2IDNo.Enabled = false;
            rfvDriver2LicenseNo.Enabled = false;

            ddlDriver1DOBDay.Enabled = false;
            ddlDriver1DOBMonth.Enabled = false;
            ddlDriver1DOBYear.Enabled = false;
            txtDriverFirst.Enabled = false;
            txtDriver1IDNo.Enabled = false;
            txtDriver1LicenseNo.Enabled = false;
            ddlDriver2DOBDay.Enabled = false;
            ddlDriver2DOBMonth.Enabled = false;
            ddlDriver2DOBYear.Enabled = false;
            txtDriverTwo.Enabled = false;
            txtDriver2IDNo.Enabled = false;
            txtDriver2LicenseNo.Enabled = false;
        }
        else if (Convert.ToInt16(ddlNamedDriver.Text) == 1)
        {
            rfvDriverFirst.Enabled = true;
            revDriverFirst.Enabled = true;
            rfvDriver1IDNo.Enabled = true;
            rfvDriver1LicenseNo.Enabled = true;
            rfvDriverTwo.Enabled = false;
            revDriverTwo.Enabled = false;
            rfvDriver2IDNo.Enabled = false;
            rfvDriver2LicenseNo.Enabled = false;

            ddlDriver1DOBDay.Enabled = true;
            ddlDriver1DOBMonth.Enabled = true;
            ddlDriver1DOBYear.Enabled = true;
            txtDriverFirst.Enabled = true;
            txtDriver1IDNo.Enabled = true;
            txtDriver1LicenseNo.Enabled = true;
            ddlDriver2DOBDay.Enabled = false;
            ddlDriver2DOBMonth.Enabled = false;
            ddlDriver2DOBYear.Enabled = false;
            txtDriverTwo.Enabled = false;
            txtDriver2IDNo.Enabled = false;
            txtDriver2LicenseNo.Enabled = false;
        }
        else if (Convert.ToInt16(ddlNamedDriver.Text) == 2)
        {
            rfvDriverFirst.Enabled = true;
            revDriverFirst.Enabled = true;
            rfvDriver1IDNo.Enabled = true;
            rfvDriver1LicenseNo.Enabled = true;
            rfvDriverTwo.Enabled = true;
            revDriverTwo.Enabled = true;
            rfvDriver2IDNo.Enabled = true;
            rfvDriver2LicenseNo.Enabled = true;

            ddlDriver1DOBDay.Enabled = true;
            ddlDriver1DOBMonth.Enabled = true;
            ddlDriver1DOBYear.Enabled = true;
            txtDriverFirst.Enabled = true;
            txtDriver1IDNo.Enabled = true;
            txtDriver1LicenseNo.Enabled = true;
            ddlDriver2DOBDay.Enabled = true;
            ddlDriver2DOBMonth.Enabled = true;
            ddlDriver2DOBYear.Enabled = true;
            txtDriverTwo.Enabled = true;
            txtDriver2IDNo.Enabled = true;
            txtDriver2LicenseNo.Enabled = true;
        }
        lblLoadMessage.Text = string.Empty;
    }

    protected void ddlOption_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblFinanceUserAlert.Text = "";
        lblCashierApproveMessage.Text = "";
        lblPayError.Text = "";
        Span1.InnerHtml = "";
        txtRemark.Text = "";
        ClearPayFields();
        lblOptionError.Text = string.Empty;
        if (ddlOption.Text == "EDIT")
        {
            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
            {
                Response.Redirect("~/carinsurance/PendingApplication.aspx");
            }

            lblOptionError.Text = string.Empty;
            lblOptionMessage.Text = string.Empty;
            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
            //LoadApplicationDetails();
            pnlDetails.Visible = true;
            pnlCarDetails.Visible = true;
            pnlPayment.Visible = false;
            pnlApplicationCancel.Visible = false;
            pnlApplicationRetrieve.Visible = false;
            pnlUploadFileList.Visible = false;
            pnlPaymentApproval.Visible = false;

            DataSet _dsPayment = GetPaymentAmounts();
            if (_dsPayment != null && _dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
            {
                txtTotalPremium.Text = _dsPayment.Tables[0].Rows[0]["TotalPremium"].ToString();
                txtCollectedAmount.Text = _dsPayment.Tables[0].Rows[0]["FinalPrice"].ToString();
                if (_dsPayment.Tables[0].Rows[0]["TotalPremium"] != DBNull.Value &&
                    _dsPayment.Tables[0].Rows[0]["TotalPremium"].ToString() != string.Empty &&
                    _dsPayment.Tables[0].Rows[0]["PaymentOption"].ToString() != "FP")
                {
                    lblBalanceAmount.Text = _dsPayment.Tables[0].Rows[0]["BalanceAmountWOD"].ToString();
                }
                else
                {
                    lblBalanceAmount.Text = _dsPayment.Tables[0].Rows[0]["BalanceAmount"].ToString();
                }
            }
            else
            {
                lblBalanceAmount.Text = txtTotalPremium.Text;
            }
            if (pnlCarDetails.Visible == true)
            {
                ddlOption.Text = "EDIT";
            }
        }
        else if (ddlOption.Text == "PAYM")
        {
            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
            {
                Response.Redirect("~/carinsurance/PendingApplication.aspx");
            }
            pnlPaymentApproval.Visible = false;
            divAgentComments.Visible = false;
            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "300")
            {
                pnlPaymentApproval.Visible = true;
                divAgentComments.Visible = true;
            }
            //Sakthi 14 Jun 2012 -Start
            chkApprove.Enabled = false;
            chkRefund.Enabled = false;
            //Sakthi 14 Jun 2012 -End
            txtOnlineApproveStatus.Text = "0";
            lblOptionError.Text = string.Empty;
            lblOptionMessage.Text = string.Empty;
            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
            pnlDetails.Visible = true;
            pnlCarDetails.Visible = false;
            pnlPayment.Visible = true;
            pnlApplicationCancel.Visible = false;
            pnlApplicationRetrieve.Visible = false;
            pnlUploadFileList.Visible = false;

            txtBalanceAmount.Text = "0";
            lblPayBalance.Text = "0";
            txtTotalCollectedAmount.Text = "0";
            txtTotalRefundAmount.Text = "0";
            DataSet _dsPayment = new DataSet();
            _dsPayment = GetBrokerPremium();
            ddlNoOfInstallments.Items.Clear();
            //ddlPaymentOption.Text = "FP";
            ddlPaymentOption.Items.Clear();
            ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));
            if (_dsPayment != null && _dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
            {
                txtAgentComments.Text = "";
                if (_dsPayment.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                {
                    txtAgentComments.Text = _dsPayment.Tables[0].Rows[0]["Info8"].ToString();
                }

                if (_dsPayment.Tables[0].Rows[0]["PaymentOption"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["PaymentOption"].ToString() != "-1")
                {
                    if (_dsPayment.Tables[0].Rows[0]["PaymentOption"].ToString().ToUpper() == "FP")
                    {
                        ddlPaymentOption.Items.Clear();
                        ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));
                    }
                    else if (_dsPayment.Tables[0].Rows[0]["PaymentOption"].ToString().ToUpper() == "IP")
                    {
                        ddlPaymentOption.Items.Clear();
                        ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Installment, "IP"));
                    }
                }
                ddlPaymentOption.Enabled = false;
                if (ddlPaymentOption.Text == "IP")
                {
                    if (_dsPayment.Tables[0].Rows[0]["NoofInstallment"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["NoofInstallment"].ToString() != "-1")
                    {
                        ddlNoOfInstallments.Items.Clear();
                        ddlNoOfInstallments.Items.Add(new ListItem(_dsPayment.Tables[0].Rows[0]["NoofInstallment"].ToString(), _dsPayment.Tables[0].Rows[0]["NoofInstallment"].ToString()));
                    }
                    if (_dsPayment.Tables[0].Rows[0]["Bank"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Bank"].ToString() != "-1")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName(_dsPayment.Tables[0].Rows[0]["Bank"].ToString()), _dsPayment.Tables[0].Rows[0]["Bank"].ToString()));
                        if (ddlIssuingBank.Text == "CHINS")
                        {
                            txtIssuingBank.Text = "Cash Installment";
                        }
                        else if (ddlIssuingBank.Text == "KBANK")
                        {
                            txtIssuingBank.Text = "Kasikorn Bank";
                        }
                        else if (ddlIssuingBank.Text == "BKK")
                        {
                            txtIssuingBank.Text = "Bangkok Bank";
                        }
                        else if (ddlIssuingBank.Text == "CITI")
                        {
                            txtIssuingBank.Text = "Citibank";
                        }
                        else if (ddlIssuingBank.Text == "KTC")
                        {
                            txtIssuingBank.Text = "KTC";
                        }
                        else if (ddlIssuingBank.Text == "AYA")
                        {
                            txtIssuingBank.Text = "Bank of Ayudhaya";
                        }
                        else if (ddlIssuingBank.Text == "CTRL")
                        {
                            txtIssuingBank.Text = "Central Card";
                        }
                        else if (ddlIssuingBank.Text == "RBSN")
                        {
                            txtIssuingBank.Text = "Robinson Card";
                        }
                        else if (ddlIssuingBank.Text == "HPRO")
                        {
                            txtIssuingBank.Text = "Homepro Card";
                        }
                    }

                    Int32 _Installments = Convert.ToInt32(ddlNoOfInstallments.Text);
                    Int32 _Install = _Installments - 1;
                    decimal IPFinalAnnualPremiumWD = 0;
                    decimal InstallmentAmountWD = 0;
                    decimal LastInstallmentAmountWD = 0;
                    decimal IPFinalAnnualPremiumWOD = 0;
                    decimal InstallmentAmountWOD = 0;
                    decimal LastInstallmentAmountWOD = 0;
                    Int32 _Approved = 0;
                    if (_dsPayment.Tables[0].Rows[0]["Approved"] != DBNull.Value)
                    {
                        if (!Int32.TryParse(_dsPayment.Tables[0].Rows[0]["Approved"].ToString(), out _Approved))
                        {
                            _Approved = 0;
                        }
                    }
                    if (_Approved == 0)
                    {
                        if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWD"] != DBNull.Value)
                        {
                            if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWD"].ToString(), out IPFinalAnnualPremiumWD))
                            {
                                IPFinalAnnualPremiumWD = 0;
                            }
                        }
                        if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWD"] != DBNull.Value)
                        {
                            if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["InstallmentAmountWD"].ToString(), out InstallmentAmountWD))
                            {
                                InstallmentAmountWD = 0;
                            }
                        }
                        if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWD"] != DBNull.Value)
                        {
                            if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["LastInstallmentAmountWD"].ToString(), out LastInstallmentAmountWD))
                            {
                                LastInstallmentAmountWD = 0;
                            }
                        }

                        if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWOD"] != DBNull.Value)
                        {
                            if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWOD"].ToString(), out IPFinalAnnualPremiumWOD))
                            {
                                IPFinalAnnualPremiumWOD = 0;
                            }
                        }
                        if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWOD"] != DBNull.Value)
                        {
                            if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["InstallmentAmountWOD"].ToString(), out InstallmentAmountWOD))
                            {
                                InstallmentAmountWOD = 0;
                            }
                        }
                        if (_dsPayment.Tables[0].Rows[0]["IPFinalAnnualPremiumWOD"] != DBNull.Value)
                        {
                            if (!decimal.TryParse(_dsPayment.Tables[0].Rows[0]["LastInstallmentAmountWOD"].ToString(), out LastInstallmentAmountWOD))
                            {
                                LastInstallmentAmountWOD = 0;
                            }
                        }

                        if (ddlIssuingBank.Text != "CHINS")
                        {
                            lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
                            lblInstallmentListTitle.Text = "1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months;
                            lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
                        }
                        else
                        {
                            lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
                            lblInstallmentListTitle.Text = "1st " + Resources.CarInsurance.Month;
                            if (_Install <= 1)
                            {
                                lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
                            }
                            else
                            {
                                lblLastInstallmentTitle.Text = "Last " + _Install + " " + Resources.CarInsurance.Months;
                            }
                        }

                        if (txtIsWD.Text == "1")
                        {
                            if (txtProviderId.Text == "29" && ddlIssuingBank.Text != "CHINS")
                            {
                                lblAmountwithInterest.Text = IPFinalAnnualPremiumWD.ToString("#.00");
                                lblInstallmentList.Text = InstallmentAmountWD.ToString("#.00");
                                lblLastInstallment.Text = LastInstallmentAmountWD.ToString("#.00");
                            }
                            else
                            {
                                lblAmountwithInterest.Text = IPFinalAnnualPremiumWOD.ToString("#.00");
                                lblInstallmentList.Text = InstallmentAmountWOD.ToString("#.00");
                                lblLastInstallment.Text = LastInstallmentAmountWOD.ToString("#.00");
                            }
                        }
                        else
                        {
                            lblAmountwithInterest.Text = IPFinalAnnualPremiumWOD.ToString("#.00");
                            lblInstallmentList.Text = InstallmentAmountWOD.ToString("#.00");
                            lblLastInstallment.Text = LastInstallmentAmountWOD.ToString("#.00");
                        }
                    }
                    else
                    {
                        decimal _FinalApprovedPrice = 0;
                        decimal _InstallmentAmount = 0;
                        decimal _1stInstallment = 0;
                        decimal _LastInstallment = 0;
                        if (txtFinalPrice.Text.Trim() != "0")
                        {
                            if (!decimal.TryParse(txtFinalPrice.Text.Trim(), out _FinalApprovedPrice))
                            {
                                _FinalApprovedPrice = 0;
                            }
                        }

                        _Installments = Convert.ToInt32(ddlNoOfInstallments.Text);
                        _Install = _Installments - 1;
                        if (ddlIssuingBank.Text != "CHINS")
                        {
                            _InstallmentAmount = Math.Ceiling(Convert.ToDecimal(_FinalApprovedPrice / _Installments));
                            _1stInstallment = Convert.ToDecimal(_InstallmentAmount * _Install);
                            _LastInstallment = Convert.ToDecimal(_FinalApprovedPrice - _1stInstallment);

                            lblAmountwithInterest.Text = _FinalApprovedPrice.ToString("#.00");
                            lblInstallmentList.Text = _InstallmentAmount.ToString("#.00");
                            lblLastInstallment.Text = _LastInstallment.ToString("#.00");

                            lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
                            lblInstallmentListTitle.Text = "1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months;
                            lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
                        }
                        else
                        {
                            decimal tempInstall = 0;
                            if (_Installments == 2)
                            {
                                tempInstall = Convert.ToDecimal(_FinalApprovedPrice / 10);
                                _LastInstallment = Math.Ceiling(Convert.ToDecimal(tempInstall * 5));
                                _1stInstallment = (_FinalApprovedPrice - _LastInstallment);
                            }
                            else if (_Installments == 3)
                            {
                                tempInstall = Convert.ToDecimal(_FinalApprovedPrice / 10);
                                _LastInstallment = Math.Ceiling(Convert.ToDecimal(tempInstall * 3));
                                _1stInstallment = (_FinalApprovedPrice - (_LastInstallment * 2));
                            }
                            else if (_Installments == 4)
                            {
                                tempInstall = Convert.ToDecimal(_FinalApprovedPrice / 4);
                                _LastInstallment = Math.Ceiling(tempInstall);
                                _1stInstallment = (_FinalApprovedPrice - (_LastInstallment * 3));
                            }

                            lblAmountwithInterest.Text = _FinalApprovedPrice.ToString("#.00");
                            lblInstallmentList.Text = _1stInstallment.ToString("#.00");
                            lblLastInstallment.Text = _LastInstallment.ToString("#.00");

                            lblAmountwithInterestTitle.Text = Resources.CarInsurance.TotalAmountwithInterest;
                            lblInstallmentListTitle.Text = "1st " + Resources.CarInsurance.Month;
                            if (_Install <= 1)
                            {
                                lblLastInstallmentTitle.Text = Resources.CarInsurance.LastMonthInstallment;
                            }
                            else
                            {
                                lblLastInstallmentTitle.Text = "Last " + _Install + " " + Resources.CarInsurance.Months;
                            }
                        }
                    }

                }
            }

            ddlPaymentOption_SelectedIndexChanged(null, null);
            ddlNoOfInstallments_SelectedIndexChanged(null, null);
            if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
            {
                grvPayment.DataSource = _dsPayment.Tables[1];
                grvPayment.DataBind();
                txtPaymentId.Text = "0";
                EnableDisable();
                if (grvPayment.Rows.Count > 0)
                {
                    chkRefund.Enabled = true;
                    chkApprove.Enabled = false;
                    DataSet _dsPaymentAmount = new DataSet();
                    _dsPaymentAmount = GetPaymentAmounts();
                    if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
                    {

                        txtTescoAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["TescoAmountShow"].ToString();

                        txtFinalApprovalPremium.Text = _dsPaymentAmount.Tables[0].Rows[0]["FinalPrice"].ToString();
                        txtTescoPaymentId.Text = _dsPaymentAmount.Tables[0].Rows[0]["TescoPaymentId"].ToString();
                        txtSpecialPaymentId.Text = _dsPaymentAmount.Tables[0].Rows[0]["SpecialPaymentId"].ToString();
                        txtApprovalRemark.Text = _dsPaymentAmount.Tables[0].Rows[0]["SpecialRemarks"].ToString();

                        txtTotalCollectedAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString();
                        txtTotalRefundAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["RefundAmount"].ToString();
                    }
                    divPayList.Visible = true;

                }
                else
                {
                    divPayList.Visible = false;
                    grvPayment.DataSource = null;
                    grvPayment.DataBind();
                }
            }
            else
            {
                txtWDPremium.Text = lblUpPremiumWD.Text;
                txtWODPremium.Text = lblUpPremiumWOD.Text;
                txtTescoPaymentId.Text = "0";
                txtSpecialPaymentId.Text = "0";
                txtApprovalRemark.Text = "";
            }
            if (txtPaymentId.Text == "0")
            {
                chkRefund.Enabled = true;
            }
            else
            {
                chkRefund.Enabled = false;
            }

            float _onlineAmount = 0.0f;
            DataSet _dsApplication = new DataSet();
            MerchantPackageDB _merchantpackagedb = new MerchantPackageDB();
            _dsApplication = _merchantpackagedb.GetCarDetails(Convert.ToInt64(txtCarId.Text.Trim()), Convert.ToInt64(txtCEId.Text.Trim()));




            if (_dsApplication.Tables[2].Rows.Count > 0 && _dsApplication.Tables[2].Rows[0]["ONLPaymentStatus"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["ONLPaymentStatus"].ToString() != string.Empty
                && _dsApplication.Tables[2].Rows[0]["ONLPaymentStatus"].ToString().ToUpper() == "1")
            {

                if (_dsApplication.Tables[2].Rows[0]["DeclineStatus"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["DeclineStatus"].ToString() != string.Empty
                && _dsApplication.Tables[2].Rows[0]["DeclineStatus"].ToString() == "1")
                {
                    pnlPaymentInput.Visible = true;
                }
                else
                {
                    PaymentsDB _paymentsdb = new PaymentsDB();
                    DataSet _dsOLPayments = new DataSet();
                    _dsOLPayments = _paymentsdb.GetPayments(Convert.ToInt64(txtCarId.Text), 1);
                    if (_dsOLPayments != null && _dsOLPayments.Tables[0].Rows.Count > 0)
                    {
                        pnlPaymentInput.Visible = true;
                        txtOnlineApproveStatus.Text = "1";
                    }
                    else
                    {
                        grvPayment.Enabled = false;
                        pnlPaymentInput.Visible = false;
                    }
                }



                if (_dsApplication.Tables[2].Rows[0]["ONLPaymentCode"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["ONLPaymentCode"].ToString() != string.Empty
                    && _dsApplication.Tables[2].Rows[0]["ONLPaymentCode"].ToString() == "1")
                {
                    if (_dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["FinalAnnualPremium"].ToString() != string.Empty)
                    {
                        txtAppStatus.Text = "OFFLINE";
                    }
                    else
                    {
                    }
                    if (_dsApplication.Tables[2].Rows[0]["OrderRefNo"] != DBNull.Value && _dsApplication.Tables[2].Rows[0]["OrderRefNo"].ToString() != string.Empty)
                    {
                    }
                    else
                    {
                    }
                }
                else
                {
                    pnlPaymentInput.Visible = true;
                }
            }
            else if (_dsApplication != null && _dsApplication.Tables.Count > 4 && _dsApplication.Tables[4].Rows.Count > 0)
            {
                if (_dsApplication.Tables[4].Rows[0]["DeclineStatus"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["DeclineStatus"].ToString() != string.Empty
                    && _dsApplication.Tables[4].Rows[0]["DeclineStatus"].ToString() == "1")
                {
                    pnlPaymentInput.Visible = true;
                }
                else
                {
                    PaymentsDB _paymentsdb = new PaymentsDB();
                    DataSet _dsOLPayments = new DataSet();
                    _dsOLPayments = _paymentsdb.GetPayments(Convert.ToInt64(txtCarId.Text), 1);
                    if (_dsOLPayments != null && _dsOLPayments.Tables[0].Rows.Count > 0)
                    {
                        pnlPaymentInput.Visible = true;
                        txtOnlineApproveStatus.Text = "1";
                    }
                    else
                    {
                        grvPayment.Enabled = false;
                        pnlPaymentInput.Visible = false;
                    }
                }



                if (_dsApplication.Tables[4].Rows[0]["PaymentType"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["PaymentType"].ToString() != string.Empty
                    && _dsApplication.Tables[4].Rows[0]["PaymentType"].ToString().ToUpper() == "CREDITCARD")
                {
                    if (_dsApplication.Tables[4].Rows[0]["PaymentCode"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["PaymentCode"].ToString() != string.Empty
                        && _dsApplication.Tables[4].Rows[0]["PaymentCode"].ToString() == "1")
                    {
                        if (_dsApplication.Tables[4].Rows[0]["AnnualPremium"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["AnnualPremium"].ToString() != string.Empty)
                        {
                            _onlineAmount = Convert.ToSingle(_dsApplication.Tables[4].Rows[0]["AnnualPremium"].ToString());
                            txtAppStatus.Text = "ONLINE";
                        }
                        else
                        {
                        }
                        if (_dsApplication.Tables[4].Rows[0]["OrderRefNo"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["OrderRefNo"].ToString() != string.Empty)
                        {
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                        grvPayment.Enabled = true;
                        pnlPaymentInput.Visible = true;
                    }
                }
                else
                {
                    if (_dsApplication.Tables[4].Rows[0]["AnnualPremium"] != DBNull.Value && _dsApplication.Tables[4].Rows[0]["AnnualPremium"].ToString() != string.Empty)
                    {
                        _onlineAmount = Convert.ToSingle(_dsApplication.Tables[4].Rows[0]["AnnualPremium"].ToString());
                        txtAppStatus.Text = "ONLINE";
                    }
                    else
                    {
                    }
                }
            }
            else
            {
                grvPayment.Enabled = true;
                pnlPaymentInput.Visible = true;
            }
            LoadLableColor();
            ShowTescoAmount();

            LoadPaymentCompletedStatus();
        }
        else if (ddlOption.Text == "UPLD")
        {
            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
            lblOptionError.Text = string.Empty;
            lblOptionMessage.Text = string.Empty;
            Span1.InnerHtml = "";
            pnlDetails.Visible = true;
            pnlUpload.Visible = true;
            pnlCarDetails.Visible = false;
            pnlPayment.Visible = false;
            pnlApplicationCancel.Visible = false;
            pnlApplicationRetrieve.Visible = false;
            pnlUploadFileList.Visible = false;
            pnlPaymentApproval.Visible = false;
            LoadUploadDocument();
        }
        else if (ddlOption.Text == "ACNL")
        {
            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
            {
                Response.Redirect("~/carinsurance/PendingApplication.aspx");
            }

            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
            pnlDetails.Visible = true;
            pnlCarDetails.Visible = false;
            pnlPayment.Visible = false;
            pnlApplicationCancel.Visible = true;
            pnlApplicationRetrieve.Visible = false;
            pnlUploadFileList.Visible = false;
            pnlPaymentApproval.Visible = false;

            DataSet _dsApplication = new DataSet();
            MerchantPackageDB _merchantpackagedb = new MerchantPackageDB();
            _dsApplication = _merchantpackagedb.GetCarDetails(Convert.ToInt64(txtCarId.Text.Trim()), Convert.ToInt64(txtCEId.Text.Trim()));
            if (_dsApplication != null && _dsApplication.Tables.Count > 2 && _dsApplication.Tables[2].Rows.Count > 0)
            {
                btnApplicationCancel.Enabled = true;
                lblOptionError.Text = string.Empty;
                lblOptionMessage.Text = string.Empty;
            }
            else
            {
                pnlOptionMessage.Visible = true;
                btnApplicationCancel.Enabled = false;
                lblOptionError.Text = Resources.General.HaveNotSubmit;
            }
        }
        else if (ddlOption.Text == "RTRV")
        {
            lblOptionError.Text = string.Empty;
            lblOptionMessage.Text = string.Empty;
            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
            pnlDetails.Visible = true;
            pnlCarDetails.Visible = false;
            pnlPayment.Visible = false;
            pnlApplicationCancel.Visible = false;
            pnlApplicationRetrieve.Visible = true;
            pnlUploadFileList.Visible = false;
            pnlPaymentApproval.Visible = false;
        }
        else if (ddlOption.Text == "0")
        {
            lblOptionError.Text = string.Empty;
            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',false);", true);
            pnlDetails.Visible = true;
            pnlCarDetails.Visible = false;
            pnlPayment.Visible = false;
            pnlApplicationCancel.Visible = false;
            pnlApplicationRetrieve.Visible = false;
            pnlUploadFileList.Visible = false;
            pnlPaymentApproval.Visible = false;
        }
        lblLoadMessage.Text = string.Empty;
    }

    protected void ddlPaymentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlPaymentType.Text == "CCOL" || ddlPaymentType.Text == "CCIP")
        {
            pnlCreditCard.Visible = true;
            pnlBank.Visible = false;
            rfvBank.Enabled = false;
        }
        else
        {
            pnlBank.Visible = false;
            rfvBank.Enabled = false;
            if (ddlPaymentType.Text == "BKTR")
            {
                pnlBank.Visible = true;
                rfvBank.Enabled = true;

                ddlBank.Items.Clear();
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankKTB, "KTB"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankSCB, "SCB"));

            }
            else if (ddlPaymentType.Text == "CHINS")
            {
                pnlBank.Visible = true;
                rfvBank.Enabled = true;

                ddlBank.Items.Clear();
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankKTB, "KTB"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.BankSCB, "SCB"));
                ddlBank.Items.Add(new ListItem(Resources.CarInsurance.Cash, "CASH"));

            }
            pnlCreditCard.Visible = false;
            if (txtPaymentId.Text != string.Empty && Convert.ToInt64(txtPaymentId.Text.Trim()) == 0)
            {
                txtCardHolder.Text = "";
                if (ddlPaymentOption.Text != "IP")
                {
                    txtIssuingBank.Text = "";
                }
                if (ddlPaymentType.Text == "CHINS")
                {
                    txtIssuingBank.Text = "";
                }
                txtCardNo1.Text = "";
                txtCardNo2.Text = "";
                txtCardNo3.Text = "";
                txtCardNo4.Text = "";
                ddlCardType.SelectedIndex = 0;
                txtCVV.Text = "000";

                txtCardExpiryMonth.Text = "";
                txtCardExpiryYear.Text = "";
            }
        }
        lblLoadMessage.Text = string.Empty;
    }

    protected void ddlPaymentOption_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlPaymentOption.Text == "IP")
        {
            if (ddlIssuingBank.Text == "CHINS")
            {
                ddlPaymentType.Items.Clear();
                ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CashInstallment, "CHINS"));
            }
            else
            {
                ddlPaymentType.Items.Clear();
                ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
                ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CreditcardiPay, "CCIP"));
                ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CreditcardAutodebit, "CCOL"));
            }

            ddlIssuingBank.Visible = true;
            divtxtIssuingBank.Visible = false;
            divddlIssuingBank.Visible = true;
            rfvIssuingBank.Enabled = false;
            rfvddlIssuingBank.Enabled = true;
            pnlNoOfInstallments.Visible = true;
            rfvNoOfInstallments.Enabled = true;

            txtAmount.Text = txtFinalPrice.Text;

        }
        else
        {
            ddlPaymentType.Items.Clear();
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.Cash, "CASH"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.BankIn, "BKTR"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CreditcardiPay, "CCIP"));
            ddlPaymentType.Items.Add(new ListItem(Resources.CarInsurance.CreditcardOnline, "CCOL"));

            ddlIssuingBank.Visible = false;
            divtxtIssuingBank.Visible = true;
            divddlIssuingBank.Visible = false;
            rfvIssuingBank.Enabled = true;
            rfvddlIssuingBank.Enabled = false;
            pnlNoOfInstallments.Visible = false;
            rfvNoOfInstallments.Enabled = false;

            txtAmount.Text = "";
            txtAmount.ReadOnly = false;
        }
        ddlPaymentType_SelectedIndexChanged(null, null);

        lblLoadMessage.Text = string.Empty;
    }

    protected void ddlIssuingBank_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlPaymentOption.Text == "IP")
        {
            if (ddlIssuingBank.Text == "KBANK")
            {
                txtIssuingBank.Text = "Kasikorn Bank";
            }
            else if (ddlIssuingBank.Text == "BKK")
            {
                txtIssuingBank.Text = "Bangkok Bank";
            }
            else if (ddlIssuingBank.Text == "CITI")
            {
                txtIssuingBank.Text = "Citibank";
            }
            else if (ddlIssuingBank.Text == "KTC")
            {
                txtIssuingBank.Text = "KTC";
            }
            else if (ddlIssuingBank.Text == "AYA")
            {
                txtIssuingBank.Text = "Bank of Ayudhaya";
            }
            else if (ddlIssuingBank.Text == "CTRL")
            {
                txtIssuingBank.Text = "Central Card";
            }
            else if (ddlIssuingBank.Text == "RBSN")
            {
                txtIssuingBank.Text = "Robinson Card";
            }
            else if (ddlIssuingBank.Text == "HPRO")
            {
                txtIssuingBank.Text = "Homepro Card";
            }
            else if (ddlIssuingBank.Text == "-1")
            {
                txtIssuingBank.Text = "";
            }
        }
    }

    protected void ddlNoOfInstallments_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlNoOfInstallments.Text != "-1")
        {
            pnlAmountwithInterest.Visible = true;


        }
        else
        {
            pnlAmountwithInterest.Visible = false;
        }
    }

    protected void btnPaySubmit_Click(object sender, EventArgs e)
    {
        lblPayError.Text = "";
        ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "CheckPaymentType();", true);
        Page.Validate("pay");
        if (txtApproveStatus.Text != string.Empty && txtApproveStatus.Text == "1" && txtPaymentId.Text != string.Empty && txtPaymentId.Text != "0")
        {
            lblPayError.Text = Resources.General.AlreadyApproved;
            lblLoadMessage.Text = string.Empty;
            return;
        }
        if (txtStatus.Text != string.Empty && txtStatus.Text.ToUpper() != "TRUE" && txtPaymentId.Text != string.Empty
            && txtPaymentId.Text != "0" && chkApprove.Checked && ddlPaymentOption.Text == "IP")
        {
            lblPayError.Text = Resources.General.PayMsg_AlreadyhaveAnnualPayments;
            lblLoadMessage.Text = string.Empty;
            return;
        }
        if (txtCashierApproved.Text != string.Empty && txtCashierApproved.Text != "0" && chkRefund.Checked == true
            && txtTescoAmount.Text != string.Empty && Convert.ToSingle(txtTescoAmount.Text.Trim()) > 0
            && (chkTescoCash.Checked == true || chkTescoVoucher.Checked == true))
        {
            lblPayError.Text = "This Premium can't allow to Refund";
            lblLoadMessage.Text = string.Empty;
            return;
        }
        Int16 _ValidatePaymentsSubmission = ValidatePaymentsSubmission(ddlPaymentOption.Text);
        if (_ValidatePaymentsSubmission > 0)
        {
            if (_ValidatePaymentsSubmission == 1)
            {
                lblPayError.Text = Resources.General.PayMsg_InstallmentAmountCantRefund;
            }
            else if (_ValidatePaymentsSubmission == 2)
            {
                lblPayError.Text = Resources.General.PayMsg_AlreadyhaveInstallmentPayments;
            }
            else if (_ValidatePaymentsSubmission == 3)
            {
                lblPayError.Text = Resources.General.PayMsg_AlreadyhaveAnnualPayments;
            }
            lblLoadMessage.Text = string.Empty;
            return;
        }

        EnablePaymentOnOff();
        lblLoadMessage.Text = string.Empty;
        if (Page.IsValid)
        {
            if (SubmitPaymentPermission())
            {
                Int16 _Valid = AmountExceedValid(1);
                if (_Valid == 1)
                {
                    Int64 _result = -1;

                    MerchantPayments _merchantpayments = new MerchantPayments();
                    MerchantPaymentsDB _merchantpaymentsdb = new MerchantPaymentsDB();

                    _merchantpayments.PaymentId = Convert.ToInt64(txtPaymentId.Text.Trim());
                    _merchantpayments.QuoteRefNo = lblPRefNo.Text;
                    _merchantpayments.CarId = Convert.ToInt64(txtCarId.Text);
                    _merchantpayments.MerchantId = Convert.ToInt64(txtMerchantId.Text);
                    _merchantpayments.ProviderCompanyId = Convert.ToInt64(txtProviderId.Text.Trim());
                    _merchantpayments.RefCEUserId = Convert.ToInt64(txtCEId.Text); //Convert.ToInt64(Session[General.UserId].ToString());
                    if (_merchantpayments.PaymentId == 0)
                    {
                        _merchantpayments.AgentId = Convert.ToInt64(Session[General.UserId].ToString());
                        _merchantpayments.AdminId = 0;
                    }
                    else
                    {
                        _merchantpayments.AgentId = 0;
                        _merchantpayments.AdminId = Convert.ToInt64(Session[General.UserId].ToString());
                    }

                    _merchantpayments.CollectedAmount = Convert.ToSingle(txtAmount.Text);
                    if (chkRefund.Checked)
                    {
                        _merchantpayments.TransactionType = 2;
                    }
                    else
                    {
                        _merchantpayments.TransactionType = 1;
                        _merchantpayments.PaymentOption = ddlPaymentOption.Text;
                        if (ddlPaymentOption.Text == "IP")
                        {
                            _merchantpayments.NoofInstallments = Convert.ToInt16(ddlNoOfInstallments.Text);
                            float AmountwithInterest = 0.0f;
                            if (!float.TryParse(lblAmountwithInterest.Text, out AmountwithInterest))
                            {
                                AmountwithInterest = 0.0f;
                            }
                            _merchantpayments.AmountwithInterest = AmountwithInterest;
                        }
                        _merchantpayments.PaymentType = ddlPaymentType.Text;
                        if (ddlPaymentType.Text == "BKTR" || ddlPaymentType.Text == "CHINS")
                        {
                            _merchantpayments.PaymentBank = ddlBank.Text;
                        }
                        _merchantpayments.CardHolder = Server.HtmlEncode(txtCardHolder.Text);
                        _merchantpayments.IssuingBank = Server.HtmlEncode(txtIssuingBank.Text);
                        if (_merchantpayments.PaymentId > 0)
                        {
                            _merchantpayments.CreditCardNo = txtCardNo1.Text.Trim() + "XXXXXXXX" + txtCardNo4.Text.Trim();
                            _merchantpayments.CVV = "XXX";
                        }
                        else
                        {
                            _merchantpayments.CreditCardNo = txtCardNo1.Text.Trim() + txtCardNo2.Text.Trim() + txtCardNo3.Text.Trim() + txtCardNo4.Text.Trim();
                            _merchantpayments.CVV = txtCVV.Text;
                        }
                        _merchantpayments.CardExpiryMonth = txtCardExpiryMonth.Text;
                        _merchantpayments.CardExpiryYear = txtCardExpiryYear.Text;
                        _merchantpayments.CardType = ddlCardType.Text;
                    }
                    if (chkApprove.Checked)
                    {
                        _merchantpayments.ApproveType = 1;
                    }
                    else
                    {
                        _merchantpayments.ApproveType = 0;
                    }

                    _merchantpayments.PaymentRefNo = Server.HtmlEncode(txtPaymentRefNo.Text);
                    _merchantpayments.IsOnlinePayment = 0;
                    Int32 noofdays = 0;
                    Int32 noofrecords = 0;
                    if (!Int32.TryParse(txtDays.Text, out noofdays))
                    {
                        noofdays = 0;
                    }
                    if (!Int32.TryParse(txtNoOfRecords.Text, out noofrecords))
                    {
                        noofrecords = 0;
                    }
                    _merchantpayments.Status = true;
                    _merchantpayments.NoOfDays = noofdays;
                    if (txtUserTypeId.Text != string.Empty)
                    {
                        _merchantpayments.UserTypeId = Convert.ToInt32(txtUserTypeId.Text);
                    }
                    _merchantpayments.Info2 = Server.HtmlEncode(txtAgentRemarks.Text);
                    _result = _merchantpaymentsdb.Insert(_merchantpayments);
                    if (_result > 0)
                    {
                        string _TescoSelectedId = "0";
                        if (chkTescoVoucher.Checked)
                        {
                            _TescoSelectedId = "1";
                        }
                        else if (chkTescoCash.Checked)
                        {
                            _TescoSelectedId = "2";
                        }
                        if (chkRefund.Checked == false)
                        {
                            MyDatabase _myDB = new MyDatabase("GG_MCDBConnectionString");
                            string _strUpdateSQL = "UPDATE tblMerchantBrokerPremium SET ";
                            _strUpdateSQL += " TescoSelect = " + _TescoSelectedId + ",";
                            _strUpdateSQL += " TescoAmount = " + txtTescoAmount.Text.Trim() + ",";
                            _strUpdateSQL += " ApprovedPremium = " + txtFinalPrice.Text.Trim();
                            _strUpdateSQL += " WHERE CarId = " + txtCarId.Text + " AND SelectedStatus = 1 AND Info1 = '" + lblUpRefNo.Text.Trim() + "'";
                            _result = _myDB.ExecuteNonSqlStatement(_strUpdateSQL);
                        }

                        if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "100")
                        {
                            string mailBody = "";
                            string _emailTitle = "";
                            string _toemail = "";
                            string _ccemail = "";
                            string _bccemail = "";
                            _emailTitle = "[" + lblUpRefNo.Text + "] " + Resources.CarInsurance.Payment + "  [" + txtPlateNumber.Text + "]";
                            mailBody = Resources.General.CustomerName + " : " + txtCustomerName.Text + "<br/><br/>";
                            mailBody += Resources.General.ReferenceNo + " : " + lblUpRefNo.Text + "<br/><br/>";
                            mailBody += Resources.CarInsurance.PaymentType + " : " + ddlPaymentType.SelectedItem.Text + "<br/><br/>";
                            mailBody += Resources.CarInsurance.Amount + " : " + txtAmount.Text + "<br/><br/>";
                            if (_merchantpayments.TransactionType == 1)
                            {
                                mailBody += Resources.General.TransactionType + " : " + Resources.CarInsurance.Payment + "<br/><br/>";
                            }
                            else if (_merchantpayments.TransactionType == 2)
                            {
                                mailBody += Resources.General.TransactionType + " : " + Resources.CarInsurance.Refund + "<br/><br/>";
                            }
                            mailBody += Resources.General.Broker + " : " + Session[CE.Global.General.UserName].ToString();
                            mailBody += "";

                            _toemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("PAYMENT"); //Add 08/Jan/2014
                            /* Hide on 08/Jan/2014
                            _toemail += CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
                            _toemail += CE.Configuration.MyConfigurationManager.GetAppSettingValue("TO_ROY");
                            _toemail += CE.Configuration.MyConfigurationManager.GetAppSettingValue("SUPERVISOR");*/
                            if (Session[General.UserRole].ToString() == "100")
                            {
                                _ccemail += Session[General.SMTPReplyTo].ToString();
                            }
                            _bccemail = "";

                            MyMailManager.SendGGMail(ConfigurationManager.AppSettings["GGFormsSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGFormsSMTPAuthCode"].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString());
                        }

                        ClearPayFields();
                        DataSet _dsPayment = new DataSet();
                        _dsPayment = GetBrokerPremium();
                        if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
                        {
                            txtAgentComments.Text = "";
                            if (_dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
                            {
                                if (_dsPayment.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                                {
                                    txtAgentComments.Text = _dsPayment.Tables[0].Rows[0]["Info8"].ToString();
                                }
                            }
                            txtBalanceAmount.Text = "0";
                            lblPayBalance.Text = "0";
                            txtTotalCollectedAmount.Text = "0";
                            txtTotalRefundAmount.Text = "0";
                            grvPayment.DataSource = _dsPayment.Tables[1];
                            grvPayment.DataBind();
                            txtPaymentId.Text = "0";
                            EnableDisable();
                            if (grvPayment.Rows.Count > 0)
                            {
                                chkRefund.Enabled = true;
                                DataSet _dsPaymentAmount = new DataSet();
                                _dsPaymentAmount = GetPaymentAmounts();
                                if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
                                {
                                    txtTotalCollectedAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString();
                                    txtTotalRefundAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["RefundAmount"].ToString();
                                }
                                divPayList.Visible = true;


                            }
                            else
                            {
                                divPayList.Visible = false;
                                grvPayment.DataSource = null;
                                grvPayment.DataBind();
                            }
                        }
                        if (txtPaymentId.Text == "0")
                        {
                            chkRefund.Enabled = true;
                        }
                        else
                        {
                            chkRefund.Enabled = false;
                        }
                        ShowTescoAmount();
                    }
                }
                else
                {
                    if (_Valid == 2)
                        lblPayError.Text = Resources.CarInsurance.ExceedCollected;
                    else if (_Valid == 3)
                        lblPayError.Text = Resources.CarInsurance.ExceedPremium;
                }
            }
            else
            {
                lblPayError.Text = Resources.Proposal.AccessDenied;
            }
        }
    }

    protected void btnPayDecline_Click(object sender, EventArgs e)
    {
        lblPayError.Text = Resources.Proposal.AccessDenied;
    }

    protected void btnPayNew_Click(object sender, EventArgs e)
    {
        ClearPayFields();

        EnablePaymentOnOff();
    }

    protected void btnApplicationCancel_Click(object sender, EventArgs e)
    {
        txtLastQuoteRefNo.Text = lblUpRefNo.Text.Trim();
        Page.Validate("appcancel");
        if (Page.IsValid)
        {
            Int64 _result = -1;
            Int16 Step = 1;
            Int64 CarId = Convert.ToInt64(txtCarId.Text);
            Int64 ProviderId = Convert.ToInt64(txtProviderId.Text.Trim());
            string Remarks = Server.HtmlEncode(txtRemark.Text.Trim());
            Int64 AgentId = Convert.ToInt64(txtAgentId.Text);
            Int64 AdminId = Convert.ToInt64(Session[General.UserId].ToString());

            MerchantPackageDB _merchantpackagedb = new MerchantPackageDB();
            _result = _merchantpackagedb.UpdateApplicationCancelStatus(CarId, ProviderId, AgentId, AdminId, Step, Remarks);
            if (_result > 0)
            {
                pnlApplicationCancel.Visible = false;
                lblOptionMessage.Text = Resources.CarInsurance.SuccessCancelApplication;
                pnlOptionMessage.Visible = true;

                txtCancelStatus.Text = "1";
                ddlOption.Items.Clear();
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "0"));
                ddlOption.Items.Add(new ListItem(Resources.CarInsurance.Retrieve, "RTRV"));
                ddlOption.SelectedIndex = 0;
                ddlOption.SelectedIndex = 0;
                ddlOption_SelectedIndexChanged(null, null);
            }
        }
    }

    protected void btnApplicationRetrieve_Click(object sender, EventArgs e)
    {
        txtLastQuoteRefNo.Text = lblUpRefNo.Text.Trim();
        if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() != "100")
        {
            if (CheckSelectedItem(lblUpRefNo.Text.ToUpper()))
            {
                Int64 _result = -1;
                Int16 Step = 2;
                Int64 CECarId = Convert.ToInt64(txtCarId.Text);
                Int64 ProviderId = Convert.ToInt64(txtProviderId.Text.Trim());
                Int64 AgentId = Convert.ToInt64(txtAgentId.Text);
                Int64 AdminId = Convert.ToInt64(Session[General.UserId].ToString());

                MerchantPackageDB _merchantpackagedb = new MerchantPackageDB();
                _result = _merchantpackagedb.UpdateApplicationRetrieveStatus(CECarId, ProviderId, AgentId, AdminId, Step, lblUpRefNo.Text.ToUpper());
                if (_result > 0)
                {
                    pnlApplicationRetrieve.Visible = false;
                    lblOptionMessage.Text = Resources.CarInsurance.SuccessRetrieveApplication;
                    pnlOptionMessage.Visible = true;
                    txtCancelStatus.Text = "0";
                    LoadOption();
                    ddlOption.SelectedIndex = 0;
                    ddlOption_SelectedIndexChanged(null, null);
                }
            }
            else
            {
                lblSearchMessage.Text = Resources.General.CheckRefNo;
            }
        }
        else
        {
            lblOptionMessage.Text = Resources.Proposal.AccessDenied;
            pnlOptionMessage.Visible = true;
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        Span1.InnerHtml = "";
        Page.Validate("upload");
        if (Page.IsValid)
        {
            if (FileUpLoad1.HasFile)
            {
                int DocNo = 1;
                Int64 _fileSize = 0;
                string _todaydate = dateTimeNow.ToString("ddMMMMyyyy"); //DateTime.Now.ToString("ddMMMMyyyy");
                string _filePath = GetPdfFilePath("documents");
                string _IsPDF = Path.GetExtension(FileUpLoad1.FileName);
                string _OriginalFile = Path.GetFileName(FileUpLoad1.FileName);
                string _fileName = ddlFileUploadType.SelectedItem.Text + "_" + txtCarId.Text.Trim() + "_" + GetRandomNo() + "_" + _todaydate;
                _fileName = _fileName.Replace(' ', '_');
                _fileSize = FileUpLoad1.FileContent.Length;
                if (_IsPDF.ToUpper() == ".PDF")
                {
                    if ((_fileSize / 1024) < 1025)
                    {
                        try
                        {
                            FileUpLoad1.PostedFile.SaveAs(_filePath + _fileName + ".pdf");

                            Int64 _uploadResult = 0;
                            //int _uploadCount = 0;
                            string _DocRefNo = "";
                            DateTime _tDate = new DateTime();
                            _tDate = dateTimeNow; //DateTime.Now;
                            _DocRefNo = _tDate.Year.ToString("0000") + _tDate.Month.ToString("00") + _tDate.Day.ToString("00") + _tDate.Hour.ToString("00") + _tDate.Minute.ToString("00") + _tDate.Second.ToString("00");
                            _DocRefNo += txtCarId.Text.Trim() + "A" + Session[General.UserId].ToString();
                            MerchantCarFileUpload _merchantcarfileupload = new MerchantCarFileUpload();
                            MerchantCarFileUploadDB _merchantcarfileuploaddb = new MerchantCarFileUploadDB();

                            _merchantcarfileupload.CarId = Convert.ToInt64(txtCarId.Text.Trim());
                            _merchantcarfileupload.ProviderCompanyId = Convert.ToInt64(txtProviderId.Text.Trim());
                            _merchantcarfileupload.InsuranceType = "CI";
                            _merchantcarfileupload.AgentId = Convert.ToInt64(Session[General.UserId].ToString());
                            _merchantcarfileupload.DocRefNo = _DocRefNo;
                            _merchantcarfileupload.DocumentNo = DocNo;
                            _merchantcarfileupload.FileTypeId = Convert.ToInt64(ddlFileUploadType.Text);
                            _merchantcarfileupload.FileName = _filePath + _fileName.ToString() + ".pdf";
                            _merchantcarfileupload.OriginalName = _OriginalFile.ToString();
                            _merchantcarfileupload.Status = true;
                            _merchantcarfileupload.TotalFiles = DocNo;
                            _uploadResult = _merchantcarfileuploaddb.Insert(_merchantcarfileupload);

                            if (_uploadResult > 0)
                            {
                                txtChassisNumber.Text = "";

                                pnlOptionMessage.Visible = true;
                                lblOptionMessage.Text = Resources.General.SuccessfullyUpdated;
                                ddlFileUploadType.SelectedIndex = 0;
                                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                                LoadUploadDocument();
                            }
                            else
                            {
                                Span1.InnerHtml = Resources.General.UploadFileNameSaveFailed;
                                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                            }
                        }
                        catch (Exception ex)
                        {
                            Span1.InnerHtml = Resources.General.FileUploadFailed;
                            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                        }
                    }
                    else
                    {
                        Span1.InnerHtml = Resources.General.Maximum1MB;
                        ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                    }
                }
                else
                {
                    Span1.InnerHtml = Resources.General.PDFformat;
                    ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
                }
            }
            else
            {
                Span1.InnerHtml = Resources.General.ChooseDocument;
                ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
            }
        }
        else
        {
            Span1.InnerHtml = Resources.General.ChooseDocument;
            ScriptManager.RegisterStartupScript(ddlOption, ddlOption.GetType(), Guid.NewGuid().ToString(), "ShowHideDiv('divUpload',true);", true);
        }
    }

    protected void btnPaymentApproval_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session[General.UserRole].ToString() == "100")
            {
                lblCashierApproveMessage.Text = Resources.Proposal.AccessDenied;
                lblCashierApproveMessage.ForeColor = System.Drawing.Color.Red;
                return;
            }
            Int32 _AppCount = 0;
            MyDatabase _myappDB = new MyDatabase("GG_MCDBConnectionString");
            string strSelectSql = "SELECT COUNT(*) RecordCount FROM tblMerchantCarMoreDetails WHERE CarId = " + txtCarId.Text + " AND QuoteRefNo = '" + lblUpRefNo.Text.Trim() + "' AND [Status] = 1";
            DataTable _SelectItemResult = _myappDB.GetDataTable(strSelectSql);
            if (_SelectItemResult != null && _SelectItemResult.Rows.Count > 0)
            {
                if (_SelectItemResult.Rows[0]["RecordCount"] != DBNull.Value)
                {
                    _AppCount = Convert.ToInt32(_SelectItemResult.Rows[0]["RecordCount"].ToString());
                }
            }
            if (_AppCount <= 0)
            {
                lblCashierApproveMessage.Text = "Application not found!";
                lblCashierApproveMessage.ForeColor = System.Drawing.Color.Red;
                return;
            }
            lblPayError.Text = "";
            lblCashierApproveMessage.Text = "";
            Page.Validate("specialpay");
            lblLoadMessage.Text = string.Empty;
            if (Page.IsValid)
            {
                if (Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() == "300")
                {
                    Int64 _result = -1;
                    Int64 CarId = 0;
                    Int64 CompanyId = 0;
                    Int64 ProviderCompanyId = 0;
                    Int16 TescoSelect = 0;
                    decimal TescoAmount = 0;
                    decimal ApprovedPremium = 0;
                    Int64 ApprovedAgentId = 0;
                    if (!Int64.TryParse(txtCarId.Text.Trim(), out CarId))
                    {
                        CarId = 0;
                    }
                    if (!Int64.TryParse(txtCEId.Text.Trim(), out CompanyId))
                    {
                        CompanyId = 0;
                    }
                    if (!Int64.TryParse(txtProviderId.Text.Trim(), out ProviderCompanyId))
                    {
                        ProviderCompanyId = 0;
                    }
                    if (!Int16.TryParse(txtTescoSelectedId.Text.Trim(), out TescoSelect))
                    {
                        TescoSelect = 0;
                    }
                    if (!decimal.TryParse(txtTescoAmount.Text.Trim(), out TescoAmount))
                    {
                        TescoAmount = 0;
                    }
                    if (!decimal.TryParse(txtFinalApprovalPremium.Text.Trim(), out ApprovedPremium))
                    {
                        ApprovedPremium = 0;
                    }
                    if (!Int64.TryParse(Session[General.UserId].ToString(), out ApprovedAgentId))
                    {
                        ApprovedAgentId = 0;
                    }
                    string _spName = "sprocMerchantCashierApprovalUpdateSingleItem";
                    SortedList _sPara = new SortedList();
                    #region Parameter
                    _sPara.Add("@CarId", CarId);
                    _sPara.Add("@ProviderCompanyId", ProviderCompanyId);
                    _sPara.Add("@TescoSelect", TescoSelect);
                    _sPara.Add("@TescoAmount", TescoAmount);
                    _sPara.Add("@ApprovedPremium", ApprovedPremium);
                    _sPara.Add("@Approved", 1);
                    _sPara.Add("@ApprovedAgentId", ApprovedAgentId);
                    _sPara.Add("@QuoteRefNo", lblUpRefNo.Text.Trim());
                    _sPara.Add("@Info9", Server.HtmlEncode(txtApprovalRemark.Text)); // Remarks
                    #endregion

                    _result = _myappDB.ExecuteSP(_spName, _sPara);

                    if (_result > 0)
                    {
                        if (txtPaymentStatus.Text.Trim() == "0")
                        {
                            string _spTName = "sprocMerchantTransactionInsertUpdateSingleItem";
                            SortedList _sTPara = new SortedList();

                            _sTPara.Add("@TransactionID", txtTransactionId.Text);
                            if (Session[General.UserRole].ToString() == "100")
                            {
                                _sTPara.Add("@AgentID", txtAgentId.Text.Trim());
                                _sTPara.Add("@AdminID", 0);
                            }
                            else
                            {
                                _sTPara.Add("@AdminID", Session[General.UserId].ToString());
                                _sTPara.Add("@AgentID", 0);
                            }
                            _sTPara.Add("@CarId", txtCarId.Text);
                            _sTPara.Add("@RefCEUserId", txtCEId.Text);
                            //_sTPara.Add("@RefCEUserId", Session[General.UserId].ToString());
                            _sTPara.Add("@MerchantId", txtMerchantId.Text);
                            _sTPara.Add("@ProviderCompanyId", txtProviderId.Text);
                            _sTPara.Add("@QuoteRefNo", lblUpRefNo.Text.Trim());
                            _sTPara.Add("@TransactionTypeId", 100);
                            _sTPara.Add("@Remarks", Server.HtmlEncode(txtApprovalRemark.Text));
                            _sTPara.Add("@Info1", null);
                            _sTPara.Add("@Info2", null);
                            _sTPara.Add("@FInfo1", null);
                            _sTPara.Add("@Status", true);
                            Int64 _transID = Convert.ToInt64(_myappDB.ExecuteNonSqlSP(_spTName, _sTPara));
                            if (_transID > 0)
                            {
                                LoadPaymentCompletedStatus();
                            }
                            else
                            {
                                lblPaymentStatusMessage.Text = "Payment Completed Status Updated Error!";
                            }
                        }

                        txtFinalPrice.Text = txtFinalApprovalPremium.Text;
                        PaymentGridLoad();
                        ShowTescoAmount();
                        lblCashierApproveMessage.Text = "Premium Updated and Payment Approved!";
                        lblCashierApproveMessage.ForeColor = System.Drawing.Color.Green;

                        string AgentEmail = "";
                        string strSql = "";
                        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
                        strSql = "SELECT Email FROM " + ConfigurationManager.AppSettings["GGCRMDB"].ToString() + "tblCEUser CU INNER JOIN ";
                        strSql += "tblMerchantBrokerPremium BP ON BP.AgentId = CU.CEID WHERE BP.SelectedStatus = 1 ";
                        strSql += "AND BP.CarId = " + txtCarId.Text + " AND BP.Info1 = '" + lblUpRefNo.Text.Trim() + "' ";
                        object _agentEmail = _db.ExecuteScalarSqlStatement(strSql);
                        if (_agentEmail != null)
                        {
                            AgentEmail = _agentEmail.ToString();
                            SendApproveMailStatusToBroker(txtCustomerName.Text, AgentEmail);
                        }
                        else
                        {
                            AgentEmail = Session[General.UserEmail].ToString();
                            SendApproveMailStatusToBroker(txtCustomerName.Text, AgentEmail);
                        }
                    }
                    else
                    {
                        lblCashierApproveMessage.Text = "Premium Updated Error!";
                        lblCashierApproveMessage.ForeColor = System.Drawing.Color.Red;
                    }
                }
                else
                {
                    lblCashierApproveMessage.Text = Resources.Proposal.AccessDenied;
                    lblCashierApproveMessage.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    public bool SendApproveMailStatusToBroker(string CustomerName, string BrokerEmail)
    {
        bool _result = true;
        string mailBody = "";
        string _emailTitle = "";
        string _toemail = "";
        string _ccemail = "";
        string _bccemail = "";
        _emailTitle = "[" + lblUpRefNo.Text + "] [Approved] ";
        mailBody = Resources.General.CustomerName + " : " + CustomerName + "<br/><br/>";
        mailBody += "Final Approval Premium : " + txtFinalApprovalPremium.Text + "<br/><br/>";
        mailBody += "Tesco : " + txtTescoAmount.Text + "<br/><br/>";
        mailBody += Resources.General.Status + " : <b style='color:green;'>" + Resources.CarInsurance.Approve + "</b><br/><br/>";
        mailBody += Resources.General.DateTime + " : " + dateTimeNow.ToString("dd-MMM-yyyy hh:mm:ss tt") + "<br/><br/>"; //DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt")
        _toemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
        if (BrokerEmail.Trim() != "broker8_renewal@comparexpress.co.th")
        {
            _toemail += BrokerEmail;
        }
        else
        {
            _toemail += "broker8@comparexpress.co.th";
        }
        _bccemail = "";

        if (Session[General.UserRole].ToString() == "100")
        {
            _ccemail += Session[General.SMTPReplyTo].ToString();
        }

        _result = MyMailManager.SendGGMail(ConfigurationManager.AppSettings["GGFormsSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGFormsSMTPAuthCode"].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString());

        return _result;
    }

    protected void grvPayment_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblPayError.Text = "";
        txtApproveStatus.Text = "0";
        if (grvPayment.Rows.Count > 0)
        {
            if (grvPayment.SelectedIndex >= 0)
            {


                btnPayDecline.Visible = true;
                btnPaySubmit.Text = Resources.CarInsurance.Approve;
                GridViewRow row = grvPayment.SelectedRow;
                txtPaymentId.Text = grvPayment.SelectedDataKey[0].ToString();
                txtStatus.Text = grvPayment.SelectedDataKey[12].ToString();
                if (grvPayment.SelectedDataKey[13] != null && grvPayment.SelectedDataKey[13].ToString() != string.Empty)
                {
                    ddlBank.Text = grvPayment.SelectedDataKey[13].ToString();
                }
                if (grvPayment.SelectedDataKey[15] != null && grvPayment.SelectedDataKey[15].ToString() != string.Empty)
                {
                    txtAgentRemarks.Text = grvPayment.SelectedDataKey[15].ToString();
                }

                rfvCVV.Enabled = false;
                revCVV.Enabled = false;
                EnableDisable();
                if (grvPayment.SelectedDataKey[3].ToString() == "1")
                {
                    chkRefund.Checked = false;
                    ddlPaymentOption.Text = grvPayment.SelectedDataKey[1].ToString();
                    ddlPaymentOption_SelectedIndexChanged(null, null);
                    ddlPaymentType.Text = grvPayment.SelectedDataKey[2].ToString();
                    ddlPaymentType_SelectedIndexChanged(null, null);
                }
                else
                {
                    chkRefund.Checked = true;
                }
                txtAmount.Text = row.Cells[3].Text;
                txtAmount.ReadOnly = true;
                if (grvPayment.SelectedDataKey[14] != null && grvPayment.SelectedDataKey[14].ToString() != string.Empty && ddlPaymentOption.Text == "IP")
                {
                    if (!chkRefund.Checked)
                    {
                        ddlNoOfInstallments.Text = grvPayment.SelectedDataKey[14].ToString();
                        ddlNoOfInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else
                {
                    ddlNoOfInstallments.Text = "-1";
                    ddlNoOfInstallments_SelectedIndexChanged(null, null);
                }
                if (grvPayment.SelectedDataKey[4].ToString() == "1")
                {

                    btnPaySubmit.Enabled = false;
                    btnPayDecline.Visible = false;
                }
                else
                {

                    btnPaySubmit.Enabled = true;
                }
                if (grvPayment.SelectedDataKey[6] != null && grvPayment.SelectedDataKey[6].ToString() != string.Empty)
                {
                    if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "kasikorn bank")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("KBANK"), "KBANK"));
                        txtIssuingBank.Text = "Kasikorn Bank";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "bangkok bank")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("BKK"), "BKK"));
                        txtIssuingBank.Text = "Bangkok Bank";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "citibank")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("CITI"), "CITI"));
                        txtIssuingBank.Text = "Citibank";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "ktc")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("KTC"), "KTC"));
                        txtIssuingBank.Text = "KTC";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "bank of ayudhaya")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("AYA"), "AYA"));
                        txtIssuingBank.Text = "Bank of Ayudhaya";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "central card")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("CTRL"), "CTRL"));
                        txtIssuingBank.Text = "Central Card";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "robinson card")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("RBSN"), "RBSN"));
                        txtIssuingBank.Text = "Robinson Card";
                    }
                    else if (grvPayment.SelectedDataKey[6].ToString().ToLower() == "homepro card")
                    {
                        ddlIssuingBank.Items.Clear();
                        ddlIssuingBank.Items.Add(new ListItem(GetBankName("HPRO"), "HPRO"));
                        txtIssuingBank.Text = "Homepro Card";
                    }
                }
                txtApproveStatus.Text = grvPayment.SelectedDataKey[4].ToString();
                chkApprove.Checked = true;
                chkApprove.Enabled = false;

                if (chkRefund.Checked == false)
                {
                    if (ddlPaymentType.Text == "CCIP" || ddlPaymentType.Text == "CCOL")
                    {
                        pnlCreditCard.Visible = true;
                        txtCardHolder.Text = grvPayment.SelectedDataKey[5].ToString();
                        txtIssuingBank.Text = grvPayment.SelectedDataKey[6].ToString();
                        if (txtOnlineApproveStatus.Text != string.Empty && txtOnlineApproveStatus.Text != "1")
                        {
                            ddlCardType.Text = grvPayment.SelectedDataKey[9].ToString();

                            txtCardExpiryMonth.Text = grvPayment.SelectedDataKey[7].ToString();
                            txtCardExpiryYear.Text = grvPayment.SelectedDataKey[8].ToString();
                        }
                        txtCVV.Text = grvPayment.SelectedDataKey[10].ToString();
                        string CC = row.Cells[2].Text;
                        for (int i = 0; i < 4; i++)
                        {
                            if (i == 0)
                            {
                                txtCardNo1.Text = CC.Substring(0, 4);
                            }
                            if (i == 1)
                            {
                                txtCardNo2.Text = CC.Substring(4, 4);
                            }
                            if (i == 2)
                            {
                                txtCardNo3.Text = CC.Substring(8, 4);
                            }
                            if (i == 3)
                            {
                                txtCardNo4.Text = CC.Substring(12, 4);
                            }
                        }
                    }
                    else
                    {
                        pnlCreditCard.Visible = false;
                        txtCardNo1.Text = "";
                        txtCardNo2.Text = "";
                        txtCardNo3.Text = "";
                        txtCardNo4.Text = "";
                        txtCardHolder.Text = "";
                        txtIssuingBank.Text = "";
                        ddlCardType.SelectedIndex = 0;
                        txtCVV.Text = "000";

                        txtCardExpiryMonth.Text = "";
                        txtCardExpiryYear.Text = "";
                    }
                }
                else
                {
                    pnlCreditCard.Visible = false;
                    txtCardNo1.Text = "";
                    txtCardNo2.Text = "";
                    txtCardNo3.Text = "";
                    txtCardNo4.Text = "";
                    txtCardHolder.Text = "";
                    txtIssuingBank.Text = "";
                    ddlCardType.SelectedIndex = 0;
                    txtCVV.Text = "000";
                    ddlPaymentType.SelectedIndex = 0;
                    ddlPaymentOption.SelectedIndex = 0;

                    txtCardExpiryMonth.Text = "";
                    txtCardExpiryYear.Text = "";
                }
                EnablePaymentOnOff();
                txtPaymentRefNo.Text = grvPayment.SelectedDataKey[11].ToString();

                if (txtPaymentId.Text == "0")
                {
                    chkRefund.Enabled = true;
                }
                else
                {
                    chkRefund.Enabled = false;
                }
            }
            else
            {
                txtPaymentId.Text = "0";
                btnPaySubmit.Text = Resources.General.Submit;
                EnableDisable();
            }
        }
        else
        {
            txtPaymentId.Text = "0";
            btnPaySubmit.Text = Resources.General.Submit;
            EnableDisable();
        }
    }

    protected void grvPayment_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string _Approve = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ApproveType"));
            string _Refund = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Transaction"));

            if (_Approve == "1")
            {
                e.Row.Cells[7].ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                e.Row.Cells[7].ForeColor = System.Drawing.Color.Red;
            }

            if (_Refund.ToUpper() == "REFUND")
            {
                e.Row.Cells[1].ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                e.Row.Cells[1].ForeColor = System.Drawing.Color.Green;
            }

            Button btnDelete = (Button)e.Row.FindControl("btnDelete");
            btnDelete.Enabled = false;
            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "300")
            {
                btnDelete.Enabled = CheckPaymentCompletedStatusDate();
            }
        }

    }



    protected void grvPayment_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Span1.InnerHtml = "";
        if (e.CommandName.Equals("MyDelete"))
        {
            if (e.CommandArgument != null)
            {
                Int64 PaymentId = 0;
                Int64 CECarId = 0;
                Int64 AdminId = 0;

                Int64 _result = -1;
                CECarId = Convert.ToInt64(txtCarId.Text);
                AdminId = Convert.ToInt64(Session[General.UserId].ToString());
                PaymentId = Convert.ToInt64(e.CommandArgument);

                NonGGPackageDB _nonggpackagedb = new NonGGPackageDB();
                _result = _nonggpackagedb.DeclineNonGGPayment(CECarId, AdminId, PaymentId);

                if (_result > 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete was successful.');", true);
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete failed.');", true);
                }
                PaymentGridLoad();
            }
        }
    }

    protected void grvFileUpload_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        Span1.InnerHtml = "";
        if (e.CommandName.Equals("MyDelete"))
        {
            if (e.CommandArgument != null)
            {
                Int64 _FileId = 0;
                Int64 _CarId = 0;
                Int64 _AgentId = 0;
                _FileId = Convert.ToInt64(e.CommandArgument);
                _CarId = Convert.ToInt64(txtCarId.Text);
                _AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());

                MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
                SortedList _paraList = new SortedList();
                _paraList.Add("@FileId", _FileId);
                _paraList.Add("@CarId", _CarId);
                _paraList.Add("@AgentId", _AgentId);
                int _effCount = _db.ExecuteNonSqlSP("sprocMerchantUploadCarFileDeleteSingleItem", _paraList);
                if (_effCount > 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete was successful.');", true);
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete failed.');", true);
                }
                GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                Label lblPath = (Label)row.FindControl("lblPath");
                MyIO _myIO = new MyIO();
                _myIO.DeleteFile(lblPath.Text);
                LoadUploadDocument();
            }
        }
    }

    protected void grvFileUpload_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink hplk = (HyperLink)e.Row.FindControl("hplDownLoad");
            Label Path = (Label)e.Row.FindControl("lblPath");

            if (hplk != null)
            {
                hplk.NavigateUrl = "DownLoad/UploadMerchantHandler.ashx?FileName=" + Path.Text;
            }

            Label FileName = (Label)e.Row.FindControl("lblPDFFileName");
            Label FileType = (Label)e.Row.FindControl("lblPDFFileType");
            string strFileName = FileName.Text;
            System.IO.FileInfo _File = new System.IO.FileInfo(strFileName.ToString());
            FileName.Text = FileType.Text.Replace(' ', '_') + "_" + lblUpRefNo.Text + "_" + (e.Row.RowIndex + 1).ToString() + _File.Extension;


        }
    }

    private bool SaveDriverDetails()
    {
        bool _result = false;
        MerchantCarDriver _merchantcardriver = new MerchantCarDriver();
        MerchantCarDriverDB _merchantcardriverdb = new MerchantCarDriverDB();

        if (ddlNamedDriver.Text != "0")
        {
            int _drivercount = Convert.ToInt32(ddlNamedDriver.Text);
            int _insertcount = 0;

            for (int i = 1; i <= _drivercount; i++)
            {
                if (Session[CE.Global.General.UserId] != null)
                {
                    _merchantcardriver.AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                }
                else
                {
                    _merchantcardriver.AgentId = 0;
                }
                //_merchantcardriver.RefCEUserId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                _merchantcardriver.CarId = Convert.ToInt64(txtCarId.Text);
                _merchantcardriver.RefCEUserId = Convert.ToInt64(txtCEId.Text);
                if (i == 1)
                {
                    _merchantcardriver.CarDriverId = Convert.ToUInt32(txtDriverId1.Text);
                    _merchantcardriver.FullName = Server.HtmlEncode(txtDriverFirst.Text.Trim());
                    DateTime _dtDriver1DOB = new DateTime(Convert.ToInt32(ddlDriver1DOBYear.Text), Convert.ToInt32(ddlDriver1DOBMonth.Text), Convert.ToInt32(ddlDriver1DOBDay.Text));
                    _merchantcardriver.DOB = _dtDriver1DOB;
                    _merchantcardriver.IDNo = Server.HtmlEncode(txtDriver1IDNo.Text.Trim());
                    _merchantcardriver.DrivingLicenseNumber = Server.HtmlEncode(txtDriver1LicenseNo.Text.Trim());
                    _merchantcardriver.Status = true;
                }
                else if (i == 2)
                {
                    _merchantcardriver.CarDriverId = Convert.ToUInt32(txtDriverId2.Text); ;
                    _merchantcardriver.FullName = Server.HtmlEncode(txtDriverTwo.Text.Trim());
                    DateTime _dtDriver2DOB = new DateTime(Convert.ToInt32(ddlDriver2DOBYear.Text), Convert.ToInt32(ddlDriver2DOBMonth.Text), Convert.ToInt32(ddlDriver2DOBDay.Text));
                    _merchantcardriver.DOB = _dtDriver2DOB;
                    _merchantcardriver.IDNo = Server.HtmlEncode(txtDriver2IDNo.Text.Trim());
                    _merchantcardriver.DrivingLicenseNumber = Server.HtmlEncode(txtDriver2LicenseNo.Text.Trim());
                    _merchantcardriver.Status = true;
                }
                if (_merchantcardriverdb.Insert(_merchantcardriver) > 0)
                {
                    _insertcount++;
                    _result = true;
                }
            }
            _merchantcardriverdb = null;
            _merchantcardriver = null;
        }
        return _result;
    }

    private string GetExcelFilePath(string CompanyId, string QuoteRefNo)
    {
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGFileOutputPath").ToString();
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        string _currentMonth = dateTimeNow.ToString("yyyyMMM"); //DateTime.Now.ToString("yyyyMMM");
        string _todaydate = dateTimeNow.ToString("yyyyMMMdd"); //DateTime.Now.ToString("yyyyMMMdd");
        _filePath += "exceloutput\\merchant\\";
        if (!_myIO.CheckDirectory(_filePath + _currentMonth))
        {
            if (_myIO.CreateDirectory(_filePath, _currentMonth))
            {
                _filePath += _currentMonth + "\\";
            }
        }
        else
        {
            _filePath += _currentMonth + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + CompanyId))
        {
            if (_myIO.CreateDirectory(_filePath, CompanyId))
            {
                _filePath += CompanyId + "\\";
            }
        }
        else
        {
            _filePath += CompanyId + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + QuoteRefNo))
        {
            if (_myIO.CreateDirectory(_filePath, QuoteRefNo))
            {
                _filePath += QuoteRefNo + "\\";
            }
        }
        else
        {
            _filePath += QuoteRefNo + "\\";
        }
        return _filePath;
    }

    private string GetPdfFilePath(string CompanyId, string QuoteRefNo)
    {
        //Currently Not Use=ing
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGFileOutputPath").ToString();
        string _currentMonth = dateTimeNow.ToString("yyyyMMM"); //DateTime.Now.ToString("yyyyMMM");
        string _todaydate = dateTimeNow.ToString("yyyyMMMdd"); //DateTime.Now.ToString("yyyyMMMdd");
        _filePath += "upload\\merchant\\";
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        if (!_myIO.CheckDirectory(_filePath + _currentMonth))
        {
            if (_myIO.CreateDirectory(_filePath, _currentMonth))
            {
                _filePath += _currentMonth + "\\";
            }
        }
        else
        {
            _filePath += _currentMonth + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + CompanyId))
        {
            if (_myIO.CreateDirectory(_filePath, CompanyId))
            {
                _filePath += CompanyId + "\\";
            }
        }
        else
        {
            _filePath += CompanyId + "\\";
        }

        if (!_myIO.CheckDirectory(_filePath + QuoteRefNo))
        {
            if (_myIO.CreateDirectory(_filePath, QuoteRefNo))
            {
                _filePath += QuoteRefNo + "\\";
            }
        }
        else
        {
            _filePath += QuoteRefNo + "\\";
        }
        return _filePath;
    }

    private string GetPdfFilePath(string FileType)
    {
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGFileOutputPath").ToString();
        _filePath += "upload\\carinsurance\\merchant\\";
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();

        string _curYear = dateTimeNow.ToString("yyyy");
        if (!_myIO.CheckDirectory(_filePath + _curYear))
        {
            if (_myIO.CreateDirectory(_filePath, _curYear))
            {
                _filePath += _curYear + "\\";
            }
        }
        else
        {
            _filePath += _curYear + "\\";
        }

        string _curMonth = dateTimeNow.ToString("MMMM");
        if (!_myIO.CheckDirectory(_filePath + _curMonth))
        {
            if (_myIO.CreateDirectory(_filePath, _curMonth))
            {
                _filePath += _curMonth + "\\";
            }
        }
        else
        {
            _filePath += _curMonth + "\\";
        }

        string _todaydate = dateTimeNow.ToString("ddMMMMyyyy");
        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        string _quotes = FileType.ToString() + "_" + _todaydate;
        if (!_myIO.CheckDirectory(_filePath + _quotes))
        {
            if (_myIO.CreateDirectory(_filePath, _quotes))
            {
                _filePath += _quotes + "\\";
            }
        }
        else
        {
            _filePath += _quotes + "\\";
        }

        return _filePath;
    }

    public void LoadUploadDocument()
    {
        MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
        string _spName = "sprocMerchantCarFileUploadDetailSelectItemList";
        string Language = "EN";
        Int16 Renewal = 0;
        if (lblLangOption.Text == "1")
            Language = "TH";
        if (ddlApplicationType.Text == "REN" || ddlApplicationType.Text == "RNO")
        {
            Renewal = 1;
        }

        SortedList _spara = new SortedList();
        _spara.Add("@CarId", Convert.ToInt64(txtCarId.Text));
        _spara.Add("@ProviderCompanyId", Convert.ToInt64(txtProviderId.Text));
        _spara.Add("@Language", Language);
        _spara.Add("@Renewal", Renewal);
        DataSet _dsUploadDocument = new DataSet();
        _dsUploadDocument = _db.GetDataSet(_spName, _spara);
        if (_dsUploadDocument != null && _dsUploadDocument.Tables.Count > 3 && _dsUploadDocument.Tables[3].Rows.Count > 0)
        {
            grvFileUpload.Visible = true;
            grvFileUpload.DataSource = _dsUploadDocument.Tables[3];
            grvFileUpload.DataBind();
            if (grvFileUpload.Rows.Count > 0)
            {
                divFileList.Visible = true;
                pnlUploadFileList.Visible = true;
            }
            else
            {
                divFileList.Visible = false;
                pnlUploadFileList.Visible = false;
            }
        }
        else
        {
            grvFileUpload.DataSource = null;
            grvFileUpload.DataBind();
            divFileList.Visible = false;
        }
    }

    public void ExportGridView(string fileName, Label lblContent)
    {
        string attachment = "attachment; filename=" + fileName + ".xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        Response.Write(lblContent.Text);
        Response.End();
    }

    private string GetRandomNo()
    {
        string _RandomNo = "";
        int _randomlen = 6;
        Random random = new Random();
        for (int i = 0; i < _randomlen; i++)
        {
            _RandomNo += random.Next(0, 9).ToString();
        }
        return _RandomNo;
    }

    public void ClearFields()
    {
        txtStatus.Text = "TRUE";
        btnPayDecline.Visible = false;
        grvPayment.Enabled = true;
        pnlPaymentInput.Visible = true;
        btnPaySubmit.Text = Resources.General.Submit;
        lblLoadMessage.Text = string.Empty;
        lblPayError.Text = "";
        pnlCarDetails.Visible = false;

        pnlDetails.Visible = false;
        lblUpApplicantName.Text = "";
        lblUpInsurer.Text = "";
        lblUpPlanName.Text = "";
        lblUpPremium.Text = "";
        lblUpPremiumWD.Text = "";
        lblUpPremiumWOD.Text = "";
        txtProviderId.Text = "";

        txtCarModelYear.Text = "";
        txtCarMakeModel.Text = "";
        txtSumInsured.Text = "";
        txtInsurancePremium.Text = "";
        txtCTPL.Text = "";
        txtTotalPremium.Text = "";
        txtCurrentInsurer.Text = "";

        txtChassisNumber.Text = "";
        txtPlateNumber.Text = "";
        txtRegistrationProvince.Text = "";
        ddlNCB.SelectedIndex = 0;
        txtInsuranceCompany.Text = "";
        txtPackage.Text = "";
        txtDriverFirst.Text = "";
        txtDriver1IDNo.Text = "";
        txtDriver1LicenseNo.Text = "";
        txtDriverTwo.Text = "";
        txtDriver2IDNo.Text = "";
        txtDriver2LicenseNo.Text = "";
        txtPrefix.Text = "";
        txtBeneficiary.Text = "";
        txtInsuredPerson.Text = "";
        txtContactNumber.Text = "";
        txtCurrentAddress.Text = "";
        txtSubDistrict.Text = "";
        txtStateProvince.Text = "";
        txtProvince.Text = "";
        txtPostalCode.Text = "";
        txtNewQuoteRefNo.Text = "";
        txtDriverId1.Text = "0";
        txtDriverId2.Text = "0";
    }

    public void LoadGarageType()
    {
        ddlGarageType.Items.Clear();
        ddlGarageType.Items.Add(new ListItem(Resources.General.Select, "-1"));
        ddlGarageType.Items.Add(new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
        ddlGarageType.Items.Add(new ListItem(Resources.CarInsurance.Garage_Dealer, "2"));
    }

    public void LoadInsuranceType()
    {
        ddlInsuranceType.Items.Clear();
        ddlInsuranceType.Items.Add(new ListItem(Resources.General.Select, "-1"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassOne, "10"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassOneLowCost, "11"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassTwoPlus, "21"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassThreePlus, "31"));
        ddlInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassThree, "30"));
    }

    public void LoadVehicleType()
    {
        ddlVehicleType.Items.Clear();
        ddlVehicleType.Items.Add(new ListItem(Resources.General.Select, "-1"));
        ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Private, "110"));
        ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Commercial, "210"));
    }

    public void LoadDate(DropDownList ddl)
    {
        string val = "";
        ddl.Items.Clear();
        for (int _date = 1; _date <= 31; _date++)
        {
            val = _date.ToString();
            if (_date < 10)
            {
                val = "0" + _date.ToString();
            }
            ddl.Items.Add(new ListItem(val, val));
        }
    }

    public void LoadMonth(DropDownList ddl)
    {
        string val = "";
        ddl.Items.Clear();

        string monthname = Resources.General.Select;
        for (int _month = 1; _month <= 12; _month++)
        {
            val = _month.ToString();
            if (_month < 10)
            {
                val = "0" + _month.ToString();
            }
            else
            {
                val = _month.ToString();
            }
            if (_month == 1)
            {
                monthname = Resources.MonthResource.January;
            }
            else if (_month == 2)
            {
                monthname = Resources.MonthResource.February;
            }
            else if (_month == 3)
            {
                monthname = Resources.MonthResource.March;
            }
            else if (_month == 4)
            {
                monthname = Resources.MonthResource.April;
            }
            else if (_month == 5)
            {
                monthname = Resources.MonthResource.May;
            }
            else if (_month == 6)
            {
                monthname = Resources.MonthResource.June;
            }
            else if (_month == 7)
            {
                monthname = Resources.MonthResource.July;
            }
            else if (_month == 8)
            {
                monthname = Resources.MonthResource.August;
            }
            else if (_month == 9)
            {
                monthname = Resources.MonthResource.September;
            }
            else if (_month == 10)
            {
                monthname = Resources.MonthResource.October;
            }
            else if (_month == 11)
            {
                monthname = Resources.MonthResource.November;
            }
            else if (_month == 12)
            {
                monthname = Resources.MonthResource.December;
            }
            //ddl.Items.Clear();
            ddl.Items.Add(new ListItem(monthname, val));
        }
    }

    public void LoadYear(DropDownList ddl, int start, int end)
    {
        string ddlval = "";
        string ddltxt = "";
        ddl.Items.Clear();
        for (int _year = start; _year <= end; _year++)
        {
            ddlval = _year.ToString();
            ddltxt = _year.ToString();
            if (lblLangOption.Text == "1")
            {
                ddltxt = (_year + 543).ToString();
            }
            ddl.Items.Add(new ListItem(ddltxt, ddlval));
        }
    }

    public void LoadOccupation()
    {
        DataTable dtOccupation = General.GetComboItem(Resources.CarInsurance.OccupationList, Resources.CarInsurance.OccupationSortBy, true);
        ddlOccupation.DataSource = dtOccupation;
        ddlOccupation.DataTextField = dtOccupation.Columns[0].ColumnName.ToString();
        ddlOccupation.DataValueField = dtOccupation.Columns[1].ColumnName.ToString();
        ddlOccupation.DataBind();
    }

    public void LoadFileUploadType()
    {
        string strKey = "";
        strKey = "EN.FileUploadType";
        if (lblLangOption.Text == "1")
        {
            strKey = "TH.FileUploadType";
        }
        DataTable dtFileUploadType = General.GetComboItem(strKey, true);
        ddlFileUploadType.DataSource = dtFileUploadType;
        ddlFileUploadType.DataTextField = dtFileUploadType.Columns[0].ColumnName.ToString();
        ddlFileUploadType.DataValueField = dtFileUploadType.Columns[1].ColumnName.ToString();
        ddlFileUploadType.DataBind();
        ddlFileUploadType.Items.Insert(0, new ListItem("Select", "-1"));
    }

    public void LoadDOB()
    {
        int intStartYear = dateTimeNow.Year - 90;
        int intEndYear = dateTimeNow.Year - 18;
        LoadDate(ddlDOBDay);
        LoadMonth(ddlDOBMonth);
        LoadYear(ddlDOBYear, intStartYear, intEndYear);

        LoadDate(ddlDriver1DOBDay);
        LoadMonth(ddlDriver1DOBMonth);
        LoadYear(ddlDriver1DOBYear, intStartYear, intEndYear);

        LoadDate(ddlDriver2DOBDay);
        LoadMonth(ddlDriver2DOBMonth);
        LoadYear(ddlDriver2DOBYear, intStartYear, intEndYear);
    }

    public void LoadCommanceDate()
    {
        int intStartYear = dateTimeNow.Year - 1;
        int intEndYear = dateTimeNow.Year + 1;
        LoadDate(ddlCommenceDay);
        LoadMonth(ddlCommenceMonth);
        LoadYear(ddlCommenceYear, intStartYear, intEndYear);
        LoadDate(ddlPolicyDay);
        LoadMonth(ddlPolicyMonth);
        LoadYear(ddlPolicyYear, intStartYear, intEndYear);
    }

    public void EnableOnOff(bool OnOff)
    {
        if (OnOff == true)
        {
            txtCarModelYear.ReadOnly = false;
            txtCarMakeModel.ReadOnly = false;
            txtCurrentInsurer.ReadOnly = false;
        }
        else if (OnOff == false)
        {
            txtCarModelYear.ReadOnly = true;
            txtCarMakeModel.ReadOnly = true;
            txtCurrentInsurer.ReadOnly = true;
        }
        ddlInsuranceType.Enabled = false;
        ddlVehicleType.Enabled = false;
        ddlGarageType.Enabled = false;
        ddlCommenceDay.Enabled = OnOff;
        ddlCommenceMonth.Enabled = OnOff;
        ddlCommenceYear.Enabled = OnOff;

        ddlPolicyDay.Enabled = OnOff;
        ddlPolicyMonth.Enabled = OnOff;
        ddlPolicyYear.Enabled = OnOff;

        ddlCTPL.Enabled = false;

        ddlDOBDay.Enabled = OnOff;
        ddlDOBMonth.Enabled = OnOff;
        ddlDOBYear.Enabled = OnOff;
        ddlGender.Enabled = OnOff;
        ddlOccupation.Enabled = OnOff;
        ddlNamedDriver.Enabled = OnOff;
    }

    public void EnablePaymentOnOff()
    {
        if (chkRefund.Checked)
        {
            rfvPaymentType.Enabled = false;
            rfvPaymentOption.Enabled = false;
            rfvNoOfInstallments.Enabled = false;
            rfvIssuingBank.Enabled = false;
            rfvCardHolder.Enabled = false;
            rfvIssuingBank.Enabled = false;
            rfvCardNo1.Enabled = false;
            revCardNo1.Enabled = false;
            rfvCardNo2.Enabled = false;
            revCardNo2.Enabled = false;
            rfvCardNo3.Enabled = false;
            revCardNo3.Enabled = false;
            rfvCardNo4.Enabled = false;
            revCardNo4.Enabled = false;
            rfvCardExpiryMonth.Enabled = false;
            rfvCardExpiryYear.Enabled = false;
            revCardExpiryMonth.Enabled = false;
            revCardExpiryYear.Enabled = false;
            csvCCExpiredValid.Enabled = false;
            rfvCardType.Enabled = false;
            rfvCVV.Enabled = false;
            revCVV.Enabled = false;
            rfvBank.Enabled = false;
        }
        else
        {
            rfvPaymentType.Enabled = true;
            rfvPaymentOption.Enabled = true;
            rfvBank.Enabled = false;
            if (ddlPaymentType.Text == "CCOL" || ddlPaymentType.Text == "CCIP")
            {
                if (chkApprove.Checked)
                {
                    rfvNoOfInstallments.Enabled = false;
                    rfvIssuingBank.Enabled = false;
                    rfvCardHolder.Enabled = false;
                    rfvIssuingBank.Enabled = false;
                    rfvCardNo1.Enabled = false;
                    revCardNo1.Enabled = false;
                    rfvCardNo2.Enabled = false;
                    revCardNo2.Enabled = false;
                    rfvCardNo3.Enabled = false;
                    revCardNo3.Enabled = false;
                    rfvCardNo4.Enabled = false;
                    revCardNo4.Enabled = false;
                    rfvCardExpiryMonth.Enabled = false;
                    rfvCardExpiryYear.Enabled = false;
                    revCardExpiryMonth.Enabled = false;
                    revCardExpiryYear.Enabled = false;
                    csvCCExpiredValid.Enabled = false;
                    rfvCardType.Enabled = false;
                    rfvCVV.Enabled = false;
                    revCVV.Enabled = false;
                }
                else
                {
                    if (ddlPaymentOption.Text == "IP")
                    {
                        rfvNoOfInstallments.Enabled = true;
                        rfvIssuingBank.Enabled = true;
                    }
                    rfvCardHolder.Enabled = true;
                    rfvIssuingBank.Enabled = true;
                    rfvCardNo1.Enabled = true;
                    revCardNo1.Enabled = true;
                    rfvCardNo2.Enabled = true;
                    revCardNo2.Enabled = true;
                    rfvCardNo3.Enabled = true;
                    revCardNo3.Enabled = true;
                    rfvCardNo4.Enabled = true;
                    revCardNo4.Enabled = true;
                    rfvCardExpiryMonth.Enabled = true;
                    rfvCardExpiryYear.Enabled = true;
                    revCardExpiryMonth.Enabled = true;
                    revCardExpiryYear.Enabled = true;
                    csvCCExpiredValid.Enabled = true;
                    rfvCardType.Enabled = true;
                    rfvCVV.Enabled = true;
                    revCVV.Enabled = true;
                }
            }
            else
            {
                if (ddlPaymentType.Text == "BKTR")
                {
                    if (chkApprove.Checked)
                    {
                        rfvBank.Enabled = false;
                    }
                    else
                    {
                        rfvBank.Enabled = true;
                    }
                }
                rfvCardHolder.Enabled = false;
                rfvIssuingBank.Enabled = false;
                rfvCardNo1.Enabled = false;
                revCardNo1.Enabled = false;
                rfvCardNo2.Enabled = false;
                revCardNo2.Enabled = false;
                rfvCardNo3.Enabled = false;
                revCardNo3.Enabled = false;
                rfvCardNo4.Enabled = false;
                revCardNo4.Enabled = false;
                rfvCardExpiryMonth.Enabled = false;
                rfvCardExpiryYear.Enabled = false;
                revCardExpiryMonth.Enabled = false;
                revCardExpiryYear.Enabled = false;
                csvCCExpiredValid.Enabled = false;
                rfvCardType.Enabled = false;
                rfvCVV.Enabled = false;
                revCVV.Enabled = false;
            }
        }
    }

    protected void csvCCExpiredValid_ServerValidate(object source, ServerValidateEventArgs args)
    {
        txtCCExpiredValid.Text = "";
        txtCCExpiredValid.Text = "valid";
        Int32 _Year = Convert.ToInt32("20" + txtCardExpiryYear.Text);
        Int32 _Month = Convert.ToInt32(txtCardExpiryMonth.Text);

        MySecurity _mysecurity = new MySecurity();
        if (_mysecurity.IsCreditCardExpiredDateValid(_Year, _Month))
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }
    }

    private void ClearPayFields()
    {
        txtStatus.Text = "TRUE";
        btnPayDecline.Visible = false;
        grvPayment.Enabled = true;
        pnlPaymentInput.Visible = true;
        btnPaySubmit.Text = Resources.General.Submit;
        lblLoadMessage.Text = string.Empty;
        txtPaymentId.Text = "0";
        EnableDisable();
        lblPayError.Text = "";
        txtAmount.Text = "";
        ddlPaymentOption.Enabled = false;
        ddlPaymentOption_SelectedIndexChanged(null, null);
        ddlPaymentType.SelectedIndex = 0;
        ddlPaymentType_SelectedIndexChanged(null, null);
        txtCardHolder.Text = "";
        txtCardNo1.Text = "";
        txtCardNo2.Text = "";
        txtCardNo3.Text = "";
        txtCardNo4.Text = "";
        txtIssuingBank.Text = "";
        txtPaymentRefNo.Text = "";
        txtCardExpiryMonth.Text = "";
        txtCardExpiryYear.Text = "";

        ddlCardType.SelectedIndex = 0;
        txtCVV.Text = "000";
        chkRefund.Checked = false;
        chkApprove.Checked = false;
        chkRefund.Enabled = true;
        chkApprove.Enabled = false;

        txtAmount.ReadOnly = false;
        divCC.Visible = false;
        rfvCVV.Enabled = true;
        revCVV.Enabled = true;
        pnlAmountwithInterest.Visible = false;
        lblAmountwithInterest.Text = "";
        lblInstallmentList.Text = "";
        txtAgentRemarks.Text = "";
    }



    private bool ChackPayValidate()
    {
        bool _IsValid = true;
        if (rfvAmount.IsValid == false)
        {
            _IsValid = false;
        }
        else if (revAmount.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvPaymentOption.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvPaymentType.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCardHolder.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvIssuingBank.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCardNo1.IsValid == false)
        {
            _IsValid = false;
        }
        else if (revCardNo1.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCardNo2.IsValid == false)
        {
            _IsValid = false;
        }
        else if (revCardNo2.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCardNo3.IsValid == false)
        {
            _IsValid = false;
        }
        else if (revCardNo3.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCardNo4.IsValid == false)
        {
            _IsValid = false;
        }
        else if (revCardNo4.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCardExpiryMonth.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCardExpiryYear.IsValid == false)
        {
            _IsValid = false;
        }
        else if (revCardExpiryMonth.IsValid == false)
        {
            _IsValid = false;
        }
        else if (revCardExpiryYear.IsValid == false)
        {
            _IsValid = false;
        }
        else if (csvCCExpiredValid.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCardType.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvCVV.IsValid == false)
        {
            _IsValid = false;
        }
        else if (revCVV.IsValid == false)
        {
            _IsValid = false;
        }
        else if (rfvPaymentRefNo.IsValid == false)
        {
            _IsValid = false;
        }
        return _IsValid;
    }

    private Int16 ValidatePaymentsSubmission(string PaymentOption)
    {
        Int16 _result = 0;
        try
        {
            DataSet _dsPaymentList = new DataSet();
            _dsPaymentList = GetApprovedPayments();
            if (_dsPaymentList != null && _dsPaymentList.Tables.Count > 0 && _dsPaymentList.Tables[0].Rows.Count > 0 && chkRefund.Checked)
            {
                _result = 1;
                decimal _balance = 0;
                if (!decimal.TryParse(txtBalanceAmount.Text, out _balance))
                {
                    _balance = 0;
                }
                if (_balance < 0)
                {
                    _result = 0;
                }
                else if (chkApprove.Checked)
                {
                    _result = 0;
                }
            }
            else if (_dsPaymentList != null && _dsPaymentList.Tables.Count > 0 && _dsPaymentList.Tables[0].Rows.Count > 0 && PaymentOption == "FP")
            {
                _result = 2;
            }
            else if (_dsPaymentList != null && _dsPaymentList.Tables.Count > 6 && _dsPaymentList.Tables[6].Rows.Count > 0 && PaymentOption == "IP")
            {
                _result = 3;
            }
            else if (_dsPaymentList != null && _dsPaymentList.Tables.Count > 0 && _dsPaymentList.Tables[0].Rows.Count > 0 && PaymentOption == "IP" && chkApprove.Checked == false && txtPaymentId.Text == "0")
            {
                _result = 2;
            }
        }
        catch (Exception ex)
        {
        }
        return _result;
    }

    public string GenerateMerchantExcel(Int64 CarId, Int64 ProviderId, string FilePath, string FileName)
    {
        string _returnFilePath = "";
        Label lblContent = new Label();
        StringBuilder strText = new StringBuilder("");
        strText.Append("<table><tr><td colspan='2'><h3>ประกันภัยรถยนต์ - แบบฟอร์ม</h3></td></tr></table>");
        DataSet _dsApplication = new DataSet();
        MerchantPackageDB _merchantpackagedb = new MerchantPackageDB();
        _dsApplication = _merchantpackagedb.GetMerchantApplication(CarId, ProviderId, 0);
        string _html = "";
        if (_dsApplication != null && _dsApplication.Tables.Count > 0 && _dsApplication.Tables[0].Rows.Count > 0)
        {

            #region Variable Declaration

            string strSql = "";
            MyDatabase _db = new MyDatabase();
            string Title, Name, DOB, Gender, Occupation, ContactNo, Email, CitizenIDnumber, PresentAddress, SubDistrict, District, Province, PostalCode, Insurer, Package, NoOfDriver;
            string InsuranceType, GarageType, CarModelYear, CarMakeModel, Size, VehicleWeight, NumberofSeat, Beneficiary, VehicleType, SumInsured, NCB;
            string CurrentInsurer, CarPlate, CarPlateProvince, EngineNumber, ChassisNumber, Modification, AnyClaims, AddDrivers, CommencementDate;
            string Premium, CTPL, CTPLAmount, TotalPremium, PaymentType, QuoteRefNo, Payment, ApplicationDate, TotalCollectedPremium, CustomerName;
            string CustomerType, CTPLStart, ProviderPremium, strLastYearRefNo, strLastYearPolicyNo, strTitle, ModificationAmount;

            float _GrossPremium = 0.0f;

            strLastYearRefNo = string.Empty;
            strLastYearPolicyNo = string.Empty;
            Title = ""; Name = ""; DOB = ""; Gender = ""; Occupation = ""; ContactNo = ""; Email = ""; CitizenIDnumber = ""; PresentAddress = ""; SubDistrict = ""; District = "";
            Province = ""; PostalCode = ""; Insurer = ""; Package = ""; NoOfDriver = ""; InsuranceType = ""; GarageType = ""; CarModelYear = "";
            CarMakeModel = ""; Size = ""; VehicleWeight = ""; NumberofSeat = ""; Beneficiary = ""; VehicleType = ""; SumInsured = ""; NCB = "";
            CurrentInsurer = ""; CarPlate = ""; CarPlateProvince = ""; EngineNumber = ""; ChassisNumber = ""; Modification = ""; AnyClaims = "";
            AddDrivers = ""; CommencementDate = ""; Premium = ""; CTPL = ""; CTPLAmount = ""; TotalPremium = ""; PaymentType = ""; CTPLStart = "";
            QuoteRefNo = ""; Payment = ""; ApplicationDate = ""; TotalCollectedPremium = ""; CustomerName = ""; CustomerType = ""; ProviderPremium = "";
            ModificationAmount = string.Empty;
            //For Driver
            string DriverName1, DriverDOB1, DriverName2, DriverDOB2, Driver1LicenseNo, Driver2LicenseNo, Driver1IDNo, Driver2IDNo;
            DriverName1 = ""; DriverDOB1 = ""; DriverName2 = ""; DriverDOB2 = ""; Driver1LicenseNo = ""; Driver2LicenseNo = "";
            Driver1IDNo = ""; Driver2IDNo = "";

            #endregion

            #region Assign Values
            strTitle = "รายละเอียดผู้ทำประกัน";
            if (ddlApplicationType.Text == "REN")
            {
                strTitle += " - ต่ออายุ";
            }
            else if (ddlApplicationType.Text == "CHB")
            {
                strTitle += " - เปลี่ยนโบรกเกอร์";
            }
            if (txtCEId.Text != string.Empty && txtCEId.Text != "0" && txtCarId.Text != string.Empty && txtCarId.Text != "0")
            {
                strLastYearRefNo = lblLastYearRefNo.Text;
                strSql = "SELECT Info2 FROM tblMerchantCarMoreDetails WHERE Info2 IS NOT NULL AND LEN(Info2) > 0 AND CarId = " + txtCarId.Text.Trim() + " AND RefCEUserId = " + txtCEId.Text.Trim();
                MyDatabase _dbM = new MyDatabase("GG_MCDBConnectionString");
                DataTable _SelectItemResult = _dbM.GetDataTable(strSql);
                if (_SelectItemResult != null && _SelectItemResult.Rows.Count > 0)
                {
                    if (_SelectItemResult.Rows[0]["Info2"] != DBNull.Value)
                    {
                        strLastYearPolicyNo = _SelectItemResult.Rows[0]["Info2"].ToString();
                    }
                }
            }
            else
            {
                strLastYearRefNo = lblLastYearRefNo.Text;
            }
            Email = _dsApplication.Tables[0].Rows[0]["Email"].ToString();
            Title = _dsApplication.Tables[0].Rows[0]["Title"].ToString();
            Name = _dsApplication.Tables[0].Rows[0]["Name"].ToString();
            CustomerName = _dsApplication.Tables[0].Rows[0]["CustomerName"].ToString();
            CustomerType = _dsApplication.Tables[0].Rows[0]["CustomerTypeTH"].ToString();
            DOB = _dsApplication.Tables[0].Rows[0]["DOB"].ToString();
            Gender = _dsApplication.Tables[0].Rows[0]["Gender"].ToString();
            Occupation = _dsApplication.Tables[0].Rows[0]["Occupation"].ToString();
            ContactNo = _dsApplication.Tables[0].Rows[0]["ContactNo"].ToString();
            Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
            if (_dsApplication.Tables[0].Rows[0]["IdentificationNo"] != DBNull.Value)
            {
                CitizenIDnumber = _dsApplication.Tables[0].Rows[0]["IdentificationNo"].ToString();
            }
            PresentAddress = _dsApplication.Tables[0].Rows[0]["PresentAddress"].ToString();
            SubDistrict = _dsApplication.Tables[0].Rows[0]["SubDistrict"].ToString();
            District = _dsApplication.Tables[0].Rows[0]["District"].ToString();
            Province = _dsApplication.Tables[0].Rows[0]["Province"].ToString();
            PostalCode = _dsApplication.Tables[0].Rows[0]["PostalCode"].ToString();
            Insurer = _dsApplication.Tables[0].Rows[0]["CompanyName"].ToString();
            Package = _dsApplication.Tables[0].Rows[0]["Package"].ToString();
            NoOfDriver = _dsApplication.Tables[0].Rows[0]["NoOfDriver"].ToString();
            if (NoOfDriver.ToString() == "0")
            {
                AddDrivers = "No";
            }
            else
            {
                AddDrivers = "Yes";
            }
            InsuranceType = _dsApplication.Tables[0].Rows[0]["InsuranceType"].ToString();
            GarageType = _dsApplication.Tables[0].Rows[0]["GarageType"].ToString();
            CarModelYear = _dsApplication.Tables[0].Rows[0]["CarModelYear"].ToString();
            CarMakeModel = _dsApplication.Tables[0].Rows[0]["CarMakeModel"].ToString();

            EngineNumber = _dsApplication.Tables[0].Rows[0]["EngineNumber"].ToString();
            ChassisNumber = _dsApplication.Tables[0].Rows[0]["ChassisNumber"].ToString();
            Beneficiary = _dsApplication.Tables[0].Rows[0]["Beneficiary"].ToString();
            VehicleType = _dsApplication.Tables[0].Rows[0]["VehicleType"].ToString();
            SumInsured = _dsApplication.Tables[0].Rows[0]["SumInsured"].ToString();
            NCB = _dsApplication.Tables[0].Rows[0]["NCB"].ToString();
            CurrentInsurer = _dsApplication.Tables[0].Rows[0]["CurrentInsurer"].ToString();
            CarPlate = _dsApplication.Tables[0].Rows[0]["CarPlate"].ToString();
            CarPlateProvince = _dsApplication.Tables[0].Rows[0]["ProvinceRegistration"].ToString();

            CommencementDate = _dsApplication.Tables[0].Rows[0]["CommencementDate"].ToString();
            Premium = _dsApplication.Tables[0].Rows[0]["Premium"].ToString();

            CTPL = _dsApplication.Tables[0].Rows[0]["CTPL"].ToString();
            CTPLAmount = _dsApplication.Tables[0].Rows[0]["CTPLAmount"].ToString();
            CTPLStart = _dsApplication.Tables[0].Rows[0]["CTPLStart"].ToString();
            TotalPremium = _dsApplication.Tables[0].Rows[0]["TotalPremium"].ToString();
            TotalCollectedPremium = _dsApplication.Tables[0].Rows[0]["TotalCollectedPremium"].ToString();
            PaymentType = _dsApplication.Tables[0].Rows[0]["PaymentType"].ToString();
            QuoteRefNo = _dsApplication.Tables[0].Rows[0]["QuoteRefNo"].ToString();
            Payment = _dsApplication.Tables[0].Rows[0]["Payment"].ToString();
            ApplicationDate = _dsApplication.Tables[0].Rows[0]["ApplicationDate"].ToString();

            if (_dsApplication.Tables[0].Rows[0]["GrossPremium"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["GrossPremium"].ToString() != string.Empty)
            {
                _GrossPremium = Convert.ToSingle(_dsApplication.Tables[0].Rows[0]["GrossPremium"].ToString());
            }
            ProviderPremium = GetProviderPremium(_GrossPremium, CTPL.ToUpper(), CTPLAmount);

            if (_dsApplication.Tables[0].Rows[0]["ModificationAmount"] != DBNull.Value && _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString() != string.Empty)
            {
                ModificationAmount = _dsApplication.Tables[0].Rows[0]["ModificationAmount"].ToString();
            }

            if (AddDrivers == "Yes")
            {
                if (_dsApplication.Tables[1].Rows.Count > 0)
                {
                    if (Convert.ToInt16(NoOfDriver) > 0)
                    {
                        DriverName1 = _dsApplication.Tables[1].Rows[0]["FullName"].ToString();
                        DriverDOB1 = _dsApplication.Tables[1].Rows[0]["DOB"].ToString();
                        Driver1IDNo = _dsApplication.Tables[1].Rows[0]["IDNo"].ToString();
                        Driver1LicenseNo = _dsApplication.Tables[1].Rows[0]["DrivingLicenseNumber"].ToString();
                    }
                    if (Convert.ToInt16(NoOfDriver) > 1)
                    {

                        DriverName2 = _dsApplication.Tables[1].Rows[1]["FullName"].ToString();
                        DriverDOB2 = _dsApplication.Tables[1].Rows[1]["DOB"].ToString();
                        Driver2IDNo = _dsApplication.Tables[1].Rows[1]["IDNo"].ToString();
                        Driver2LicenseNo = _dsApplication.Tables[1].Rows[1]["DrivingLicenseNumber"].ToString();
                    }
                }
            }

            #endregion

            #region Generate Excel File
            _html += "<html><body><table width='60%' cellpadding='1' cellspacing='1' border='1'>";
            if (ddlApplicationType.Text == "REN")
            {
                _html += "<tr><td width='20%' align='left' colspan='2'><b>" + strTitle + "</b></td></tr>";
                _html += "<tr><td width='300' align='left'><b>เลขที่อ้างอิงปีที่แล้ว</b></td><td  align='left'>" + strLastYearRefNo.ToString() + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>เลขที่กรมธรรม์ปีที่แล้ว</b></td><td  align='left'>" + strLastYearPolicyNo.ToString() + "</td></tr>";
            }
            else if (ddlApplicationType.Text == "CHB")
            {
                _html += "<tr><td width='20%' align='left' colspan='2'><b>" + strTitle + "</b></td></tr>";
                _html += "<tr><td width='300' align='left'><b>เลขที่กรมธรรม์ปีที่แล้ว</b></td><td  align='left'>" + strLastYearPolicyNo.ToString() + "</td></tr>";
            }
            else
            {
                _html += "<tr><td width='20%' align='left' colspan='2'><b>รายละเอียดผู้ทำประกัน</b></td></tr>";
            }

            _html += "<tr><td width='300' align='left'><b>ประเภทลูกค้า</b></td><td  align='left'>" + CustomerType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>คำนำหน้า</b></td><td  align='left'>" + Title + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ชื่อผู้ทำประกัน</b></td><td  align='left'>" + Name + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>วันเกิด</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + DOB + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เพศ</b></td><td  align='left'>" + Gender + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>อาชีพ</b></td><td  align='left'>" + Occupation + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เบอร์ติดต่อ</b></td><td style='mso-number-format:\\@' align='left'>" + ContactNo + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เลขที่บัตรประชาชน</b></td><td align='left'>" + CitizenIDnumber + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ที่อยู่ปัจจุบัน</b></td><td  align='left'>" + PresentAddress + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>แขวง/ตำบล</b></td><td  align='left'>" + SubDistrict + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เขต/อำเภอ</b></td><td  align='left'>" + District + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>จังหวัด</b></td><td  align='left'>" + Province + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>รหัสไปรษณีย์</b></td><td  align='left'>" + PostalCode + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>บริษัทประกัน</b></td><td  align='left'>" + Insurer + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>แพกเก็จ</b></td><td  align='left'>" + Package + "</td></tr>";

            _html += "<tr><td width='300' align='left'><b>ระบุผู้ขับขี่</b></td><td  align='left'>" + AddDrivers + "</td></tr>";
            if (AddDrivers == "Yes")
            {
                _html += "<tr><td width='300' align='left'><b>จำนวนผู้ขับขี่</b></td><td  align='left'>" + NoOfDriver + "</td></tr>";
            }
            if (Convert.ToInt16(NoOfDriver) > 0)
            {
                _html += "<tr><td width='300' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 1</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB1 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1</b></td><td  align='left'>" + DriverName1 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver1IDNo + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 1 เลขที่ใบขับขี่</b></td><td  align='left'>" + Driver1LicenseNo + "</td></tr>";
            }
            if (Convert.ToInt16(NoOfDriver) > 1)
            {
                _html += "<tr><td width='300' align='left'><b>วันเกิด ผู้ขับขี่คนที่ 2</b></td><td  style='mso-number-format:dd\\-mmm\\-yyyy' align='left'>" + DriverDOB2 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2</b></td><td  align='left'>" + DriverName2 + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่บัตรประชาชน</b></td><td style='mso-number-format:\\@' align='left'>" + Driver2IDNo + "</td></tr>";
                _html += "<tr><td width='300' align='left'><b>ผู้ขับขี่คนที่ 2 เลขที่ใบขับข</b></td><td  align='left'>" + Driver2LicenseNo + "</td></tr>";
            }
            _html += "<tr><td width='300' align='left'><b>ประเภทประกัน</b></td><td  align='left'>" + InsuranceType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ประเภทอู่</b></td><td  align='left'>" + GarageType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ปีของรถ</b></td><td  align='left'>" + CarModelYear + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>รุ่น</b></td><td  align='left'>" + CarMakeModel + "</td></tr>";

            _html += "<tr><td width='300' align='left'><b>ผู้รับผลประโยชน์</b></td><td  align='left'>" + Beneficiary + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ประเภทรถ</b></td><td  align='left'>" + VehicleType + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ทุนประกัน</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + SumInsured + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ส่วนลด NCB</b></td><td  align='left'>" + NCB + "</td></tr>";
            if (ModificationAmount.ToString() != string.Empty && ModificationAmount.ToString() != "")
            {
                _html += "<tr><td width='300' align='left'><b>อุปกรณ์หรือการปรับเปลี่ยนค่าใช้จ่าย</b></td><td  align='left'>" + ModificationAmount + "</td></tr>";
            }
            _html += "<tr><td width='300' align='left'><b>บริษัทประกันปัจจุบัน</b></td><td  align='left'>" + CurrentInsurer + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ทะเบียนรถ</b></td><td  align='left'>" + CarPlate + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>จังหวัดที่จดทะเบียน</b></td><td  align='left'>" + CarPlateProvince + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>หมายเลขเครื่อง</b></td><td  align='left'>" + EngineNumber + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>หมายเลข Chassis</b></td><td  align='left'>" + ChassisNumber + "</td></tr>";

            _html += "<tr><td width='300'  align='left'><b>วันเริ่มคุ้มครอง (ภาคสมัครใจ)</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + CommencementDate + "</td></tr>";

            _html += "<tr><td width='300' align='left'><b>เบี้ยประกันภาคสมัครใจ</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + _GrossPremium.ToString() + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>ซื้อ พ.ร.บ. หรือไม่</b></td><td  align='left'>" + CTPL + "</td></tr>";
            if (CTPL == "Yes")
            {
                _html += "<tr><td width='300' align='left'><b>เบี้ย พ.ร.บ.</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00'  align='left'>" + CTPLAmount + "</td></tr>";
            }
            else
            {
                _html += "<tr><td width='300' align='left'><b>เบี้ย พ.ร.บ.</b></td><td align='left'>-</td></tr>";
            }
            _html += "<tr><td width='300'  align='left'><b>วันที่ พ.ร.บ.เริ่มคุ้มครอง</b></td><td style='mso-number-format:dd\\-mmm\\-yyyy'  align='left'>" + CTPLStart + "</td></tr>";
            _html += "<tr><td width='300' align='left'><b>เบี้ยประกันรวมทั้งหมด</b></td><td style='mso-number-format:\\#\\,\\#\\#0\\.00' align='left'>" + ProviderPremium + "</td></tr>";

            _html += "<tr><td width='300' align='left'><b>วันที่ทำรายการ</b></td><td style='mso-number-format:dd\\/mm\\/yyyy\\ hh\\:mm\\' align='left'>" + dateTimeNow.ToString("dd/MM/yyyy hh:mm", new System.Globalization.CultureInfo("en-US")) + "</td></tr>"; //ตาม วัน/เวลา ที่ปรากฎในอีเมล์

            _html += "</table></body></html>";
            #endregion

            lblContent.Text = _html;
            MyIO myio = new MyIO();

            string[] filecontent = new string[1];
            filecontent[0] = lblContent.Text.ToString();

            myio.WriteNewFile(FilePath, FileName + ".xls", filecontent);
            _returnFilePath = FilePath + FileName + ".xls";
        }
        return _returnFilePath;
    }

    public Int16 AmountExceedValid(Int16 Process)
    {
        string i = txtTotalRefundAmount.Text;
        Int16 _IsValid = 1;
        float Premium = 0;
        float Collected = 0;
        float Amount = 0;
        float Refund = 0;
        float Balance = 0;
        if (txtFinalPrice.Text != "")
            Premium = Convert.ToSingle(txtFinalPrice.Text);
        if (txtTotalCollectedAmount.Text != "")
            Collected = Convert.ToSingle(txtTotalCollectedAmount.Text);
        if (txtAmount.Text != "")
            Amount = Convert.ToSingle(txtAmount.Text);
        if (txtTotalRefundAmount.Text != "")
            Refund = Convert.ToSingle(txtTotalRefundAmount.Text);
        if (txtBalanceAmount.Text != "")
            Balance = Convert.ToSingle(txtBalanceAmount.Text);
        if (Process == 1)
        {
            if (chkApprove.Checked == false)
            {
                if (chkRefund.Checked)
                {
                    if (Collected < (Amount))
                    {
                        _IsValid = 2;
                    }
                }
                else
                {
                    float _calAmount = Collected + Amount;
                    if (Premium < _calAmount)
                    {
                        _IsValid = 3;
                    }
                    else if (Amount > Balance)
                    {
                        _IsValid = 3;
                    }


                    if (Premium == _calAmount)
                    {
                        _IsValid = 1;
                    }

                }
            }
        }
        if (Process == 2)
        {
            _IsValid = 0;
            DataSet _dsPaymentAmount = new DataSet();
            _dsPaymentAmount = GetPaymentAmounts();
            if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
            {
                Premium = 0;
                Collected = 0;
                if (_dsPaymentAmount.Tables[0].Rows[0]["PremiumAmount"].ToString() != null && _dsPaymentAmount.Tables[0].Rows[0]["PremiumAmount"].ToString() != "")
                    Premium = Convert.ToSingle(_dsPaymentAmount.Tables[0].Rows[0]["PremiumAmount"].ToString());
                if (_dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString() != null && _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString() != "")
                    Collected = Convert.ToSingle(_dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString());
                if (Premium > 0 && Premium == Collected)
                {
                    _IsValid = 1;
                }
            }
        }
        if (Process == 3)
        {
            float _calAmount = (Collected - Refund) + Amount;

            if (Premium < _calAmount)
            {
                _IsValid = 4;
            }
            else if (Amount > Balance)
            {
                _IsValid = 4;
            }

        }
        return _IsValid;
    }

    public DataSet GetTransaction(string QuoteRefNo, Int16 TransactionTypeId)
    {
        DataSet _dsTransaction = new DataSet();
        MerchantTransactionDB _merchanttransactiondb = new MerchantTransactionDB();
        _dsTransaction = _merchanttransactiondb.GetTransaction(QuoteRefNo, TransactionTypeId);
        return _dsTransaction;
    }

    public bool SubmitPaymentPermission()
    {
        bool _Valid = true;
        if (txtPaymentId.Text != "" && txtPaymentId.Text != "0" && chkApprove.Checked && Session[CE.Global.General.UserRole] != null && Session[CE.Global.General.UserRole].ToString() != "300")
        {
            _Valid = false;
        }
        if (lblMailingStatus.Text != string.Empty && lblMailingStatus.Text == "1")
        {
            _Valid = false;
        }
        return _Valid;
    }

    public string GetColor(string ApproveType)
    {
        string color = "red";
        if (ApproveType == "1")
        {
            color = "green";
        }
        return color;
    }

    public void LoadLableColor()
    {
        try
        {
            DataSet _dsPayment = new DataSet();
            DateTime _PremiumDate = dateTimeNow;
            DateTime _PremiumWDDate = dateTimeNow;
            DateTime _CurrentDate = dateTimeNow;
            TimeSpan ts;
            Int32 days = 0;
            Int32 noofrecords = 0;
            txtIsWD.Text = "1";
            Int64 Provider = 0;
            Int32 CoverType = 10;
            string PaymentOption = "FP";

            _dsPayment = GetApprovedPayments();// GetBrokerPremium();
            if (_dsPayment != null && _dsPayment.Tables.Count > 14 && _dsPayment.Tables[14].Rows.Count > 0)
            {
                txtNoOfRecords.Text = _dsPayment.Tables[14].Rows.Count.ToString();
                if (!Int32.TryParse(txtNoOfRecords.Text, out noofrecords))
                {
                    noofrecords = 0;
                }
            }

            if (_dsPayment != null && _dsPayment.Tables.Count > 15 && _dsPayment.Tables[15].Rows.Count > 0)
            {
                if (!DateTime.TryParse(_dsPayment.Tables[15].Rows[0]["ModifiedDate"].ToString(), out _PremiumDate))
                {
                    _PremiumDate = dateTimeNow;
                }
                if (!Int64.TryParse(_dsPayment.Tables[15].Rows[0]["CXBrokerProviderId"].ToString(), out Provider))
                {
                    Provider = 0;
                }
                if (!Int32.TryParse(_dsPayment.Tables[15].Rows[0]["ProviderCoverTypeId"].ToString(), out CoverType))
                {
                    CoverType = 10;
                }
                if (_dsPayment.Tables[15].Rows[0]["PaymentOption"] != DBNull.Value)
                {
                    PaymentOption = _dsPayment.Tables[15].Rows[0]["PaymentOption"].ToString();
                }

                if (Provider == 29 || PaymentOption == "FP")
                {
                    ts = (_CurrentDate.Date - _PremiumDate.Date);
                    days = ts.Days;

                    if (noofrecords == 0)
                    {
                        if (days > 7)
                        {
                            lblPreAmtTitle.ForeColor = System.Drawing.Color.Black;
                            lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Green;

                            lblPreAmtTitle.Font.Bold = false;
                            lblPreAmtWODTitle.Font.Bold = true;

                            txtIsWD.Text = "0";
                        }
                        else
                        {
                            lblPreAmtTitle.ForeColor = System.Drawing.Color.Green;
                            lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Black;

                            lblPreAmtTitle.Font.Bold = true;
                            lblPreAmtWODTitle.Font.Bold = false;

                            txtIsWD.Text = "1";
                        }

                    }
                    else
                    {
                        if (_dsPayment.Tables[15].Rows[0]["FInfo1"] != DBNull.Value)
                        {
                            if (_dsPayment.Tables[15].Rows[0]["FInfo1"].ToString() == _dsPayment.Tables[15].Rows[0]["FinalAnnualPremium"].ToString())
                            {
                                lblPreAmtTitle.ForeColor = System.Drawing.Color.Black;
                                lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Green;

                                lblPreAmtTitle.Font.Bold = false;
                                lblPreAmtWODTitle.Font.Bold = true;

                                txtIsWD.Text = "0";
                            }
                            else
                            {
                                lblPreAmtTitle.ForeColor = System.Drawing.Color.Green;
                                lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Black;

                                lblPreAmtTitle.Font.Bold = true;
                                lblPreAmtWODTitle.Font.Bold = false;

                                txtIsWD.Text = "1";
                            }
                        }
                        else
                        {
                            lblPreAmtTitle.ForeColor = System.Drawing.Color.Green;
                            lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Black;

                            lblPreAmtTitle.Font.Bold = true;
                            lblPreAmtWODTitle.Font.Bold = false;

                            txtIsWD.Text = "1";
                        }
                    }
                }
                else
                {
                    lblPreAmtTitle.ForeColor = System.Drawing.Color.Black;
                    lblPreAmtWODTitle.ForeColor = System.Drawing.Color.Green;

                    lblPreAmtTitle.Font.Bold = false;
                    lblPreAmtWODTitle.Font.Bold = true;

                    txtIsWD.Text = "0";
                }

                txtDays.Text = days.ToString();
            }

        }
        catch (Exception ex)
        {
        }
    }

    public void EnableDisable()
    {
        bool Enable = true;
        if (txtPaymentId.Text != string.Empty && Convert.ToInt64(txtPaymentId.Text.Trim()) > 0)
        {
            Enable = false;
        }
        ddlPaymentType.Enabled = Enable;
        ddlPaymentOption.Enabled = Enable;
        ddlNoOfInstallments.Enabled = Enable;
        ddlIssuingBank.Enabled = Enable;
        ddlBank.Enabled = Enable;
        txtCardHolder.Enabled = Enable;
        txtIssuingBank.Enabled = Enable;
        txtCardNo1.Enabled = Enable;
        txtCardNo2.Enabled = Enable;
        txtCardNo3.Enabled = Enable;
        txtCardNo4.Enabled = Enable;

        txtCardExpiryMonth.Enabled = Enable;
        txtCardExpiryYear.Enabled = Enable;

        ddlCardType.Enabled = Enable;
        txtCVV.Enabled = Enable;

    }

    public bool SendApproveMailToAdmin(Int16 TransactionType, string CustomerName, string Amount, string BrokerEmail, Int16 Status)
    {
        bool _result = true;
        string mailBody = "";
        string _emailTitle = "";
        string _toemail = "";
        string _ccemail = "";
        string _bccemail = "";
        _emailTitle = "[" + lblUpRefNo.Text + "] " + Resources.CarInsurance.Payment + "  [" + txtPlateNumber.Text + "]";
        mailBody = Resources.General.CustomerName + " : " + CustomerName + "<br/><br/>";
        mailBody += Resources.CarInsurance.Amount + " : " + Amount + "<br/><br/>";
        if (TransactionType == 1)
        {
            mailBody += Resources.General.TransactionType + " : " + Resources.CarInsurance.Payment + "<br/><br/>";
        }
        else if (TransactionType == 2)
        {
            mailBody += Resources.General.TransactionType + " : " + Resources.CarInsurance.Refund + "<br/><br/>";
        }
        if (Status == 1)
        {
            mailBody += Resources.General.Status + " : <b style='color:green;'>" + Resources.CarInsurance.Approve + "</b><br/><br/>";
        }
        else if (Status == 0)
        {
            mailBody += Resources.General.Status + " : <b style='color:red;'>" + Resources.General.Decline + "</b><br/><br/>";
        }
        mailBody += Resources.General.DateTime + " : " + dateTimeNow.ToString("dd-MMM-yyyy hh:mm:ss tt") + "<br/><br/>";
        _toemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
        _toemail += BrokerEmail;
        _bccemail = "";

        if (Session[General.UserRole].ToString() == "100")
        {
            _ccemail += Session[General.SMTPReplyTo].ToString();
        }

        _result = MyMailManager.SendGGMail(ConfigurationManager.AppSettings["GGFormsSMTPAccount"].ToString(), ConfigurationManager.AppSettings["GGFormsSMTPAuthCode"].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString());

        return _result;
    }

    private string GetSMTPAccount(string smtpKey)
    {
        string _retValue = string.Empty;

        if (smtpKey == "admin")
        {
            _retValue = ConfigurationManager.AppSettings["ADMIN"].ToString();
        }
        else if (smtpKey == "cashier")
        {
            _retValue = ConfigurationManager.AppSettings["CASH"].ToString();
        }
        else if (smtpKey == "broker1")
        {
            _retValue = ConfigurationManager.AppSettings["Broker1ReplyTo"].ToString();
        }
        else if (smtpKey == "broker2")
        {
            _retValue = ConfigurationManager.AppSettings["Broker2ReplyTo"].ToString();
        }
        else if (smtpKey == "broker3")
        {
            _retValue = ConfigurationManager.AppSettings["Broker3ReplyTo"].ToString();
        }
        else if (smtpKey == "broker4")
        {
            _retValue = ConfigurationManager.AppSettings["Broker4ReplyTo"].ToString();
        }
        else if (smtpKey == "broker5")
        {
            _retValue = ConfigurationManager.AppSettings["Broker5ReplyTo"].ToString();
        }
        else if (smtpKey == "broker6")
        {
            _retValue = ConfigurationManager.AppSettings["Broker6ReplyTo"].ToString();
        }
        else if (smtpKey == "broker7")
        {
            _retValue = ConfigurationManager.AppSettings["Broker7ReplyTo"].ToString();
        }

        return _retValue;
    }

    private string GetProviderPremium(float NetPremium, float Discount, string CTPL, string CTPLAmount)
    {
        string _retValue = string.Empty;
        try
        {
            if (CTPL.ToString() == string.Empty)
            {
                CTPL = "NO";
            }
            if (CTPLAmount.ToString() == string.Empty)
            {
                CTPLAmount = "0";
            }
            decimal _netPremium = Convert.ToDecimal(NetPremium.ToString());

            decimal _tax = 0;
            _tax = Convert.ToDecimal(_netPremium * (0.4M / 100.0M));
            _tax = Convert.ToDecimal(_tax.ToString("#.00"));

            decimal _vat = 0;
            decimal _vatamt1 = 0;
            decimal _vatamt2 = 0;
            _vatamt1 = Convert.ToDecimal((_netPremium + _tax).ToString("#.00"));
            _vatamt2 = Convert.ToDecimal(7.0M / 100.0M);
            _vat = Convert.ToDecimal(_vatamt1 * _vatamt2);

            _vat = Convert.ToDecimal(_vat.ToString("#.00"));


            decimal _annualPremium = 0;

            if (Discount > 0)
            {
                decimal _discountAmount = Convert.ToDecimal((_netPremium * Convert.ToDecimal(Convert.ToDecimal(Discount) / 100.0M)));
                _annualPremium = _netPremium - _discountAmount;
                _annualPremium = _annualPremium + _vat + Math.Ceiling(_tax); ;
            }
            else
            {
                _annualPremium = _netPremium + _vat + Math.Ceiling(_tax);
            }

            if (CTPL == "YES")
            {
                _annualPremium = _annualPremium + Math.Ceiling(Convert.ToDecimal(CTPLAmount.ToString()));
            }
            _retValue = _annualPremium.ToString("#.00");
        }
        catch (Exception Ex)
        {
            Ex = null;
        }

        return _retValue;
    }

    private string GetProviderPremium(float GrossPremium, string CTPL, string CTPLAmount)
    {
        string _retValue = string.Empty;
        try
        {
            if (CTPL.ToString() == string.Empty)
            {
                CTPL = "NO";
            }
            if (CTPLAmount.ToString() == string.Empty)
            {
                CTPLAmount = "0";
            }
            decimal _grossPremium = Convert.ToDecimal(GrossPremium.ToString());
            if (CTPL == "YES")
            {
                _grossPremium = _grossPremium + Convert.ToDecimal(CTPLAmount.ToString());
            }
            _retValue = _grossPremium.ToString("#.00");
        }
        catch (Exception Ex)
        {
            Ex = null;
        }

        return _retValue;
    }

    private string GetBankName(string BankCode)
    {
        string _BankName = string.Empty;

        if (BankCode == "CHINS")
        {
            _BankName = Resources.CarInsurance.CashInstallment;
        }
        else if (BankCode == "BKK")
        {
            _BankName = Resources.CarInsurance.BankBKK;
        }
        else if (BankCode == "CITI")
        {
            _BankName = Resources.CarInsurance.BankCITI;
        }
        else if (BankCode == "KBANK")
        {
            _BankName = Resources.CarInsurance.BankK;
        }
        else if (BankCode == "KTC")
        {
            _BankName = Resources.CarInsurance.BankKTC;
        }
        else if (BankCode == "AYA")
        {
            _BankName = Resources.CarInsurance.BankAYA;
        }
        else if (BankCode == "CTRL")
        {
            _BankName = Resources.CarInsurance.CentralCard;
        }
        else if (BankCode == "RBSN")
        {
            _BankName = Resources.CarInsurance.RobinsonCard;
        }
        else if (BankCode == "HPRO")
        {
            _BankName = Resources.CarInsurance.HomeproCard;
        }
        else
        {
            _BankName = Resources.CarInsurance.Select;
        }

        return _BankName;
    }

    private void PaymentGridLoad()
    {
        DataSet _dsPayment = new DataSet();
        _dsPayment = GetBrokerPremium();
        if (_dsPayment != null && _dsPayment.Tables.Count > 1 && _dsPayment.Tables[1].Rows.Count > 0)
        {
            txtAgentComments.Text = "";
            if (_dsPayment != null && _dsPayment.Tables.Count > 0 && _dsPayment.Tables[0].Rows.Count > 0)
            {
                if (_dsPayment.Tables[0].Rows[0]["Info8"] != DBNull.Value && _dsPayment.Tables[0].Rows[0]["Info8"].ToString() != string.Empty)
                {
                    txtAgentComments.Text = _dsPayment.Tables[0].Rows[0]["Info8"].ToString();
                }
            }
            txtBalanceAmount.Text = "0";
            lblPayBalance.Text = "0";
            txtTotalCollectedAmount.Text = "0";
            txtTotalRefundAmount.Text = "0";
            grvPayment.DataSource = _dsPayment.Tables[1];
            grvPayment.DataBind();
            txtPaymentId.Text = "0";
            EnableDisable();
            if (grvPayment.Rows.Count > 0)
            {
                chkRefund.Enabled = true;
                DataSet _dsPaymentAmount = new DataSet();
                _dsPaymentAmount = GetPaymentAmounts();
                if (_dsPaymentAmount != null && _dsPaymentAmount.Tables.Count > 0 && _dsPaymentAmount.Tables[0].Rows.Count > 0)
                {
                    txtTotalCollectedAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["CollectedAmount"].ToString();
                    txtTotalRefundAmount.Text = _dsPaymentAmount.Tables[0].Rows[0]["RefundAmount"].ToString();
                }
                divPayList.Visible = true;

            }
            else
            {
                divPayList.Visible = false;
                grvPayment.DataSource = null;
                grvPayment.DataBind();
            }
        }
    }

    private void ShowTescoAmount()
    {
        string strCommence = "";
        string minPremium = "0";
        decimal _Premium = 0;

        DataTable dt = new DataTable();
        DataSet _dsSelect = new DataSet();
        DataTable _dtSelect = new DataTable();
        DateTime _CoverCommDate = dateTimeNow;
        DateTime _CurrentDate = dateTimeNow;
        TimeSpan ts;
        Int32 days = 0;
        Int32 RecordCount = 0;
        if (ddlApplicationType.Text == "REN" || ddlApplicationType.Text == "RNO")
        {
            lblTescoSelection.Text = "N/A";
            txtTescoSelectedId.Text = "0";
            txtTescoAmount.Text = "0.00";
            txtHideTescoWD.Text = "0";
            txtHideTescoWOD.Text = "0";
            chkTescoVoucher.Checked = false;
            chkTescoCash.Checked = false;
        }
        else
        {
            MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
            SortedList _sPara = new SortedList();
            string _spName = "sprocMerchantTescoAmountSelectedByCarId";
            _sPara.Add("@CarId", Convert.ToInt64(txtCarId.Text.Trim()));
            _sPara.Add("@ProviderId", Convert.ToInt64(txtProviderId.Text));
            _dsSelect = _db.GetDataSet(_spName, _sPara);
            if (_dsSelect != null && _dsSelect.Tables.Count > 0)
            {
                txtHideTescoWD.Text = "0";
                txtHideTescoWOD.Text = "0";
                RecordCount = Convert.ToInt32(_dsSelect.Tables[0].Rows[0]["RecordCount"].ToString());
                if (RecordCount > 0)
                {
                    if (_dsSelect.Tables.Count > 1)
                    {
                        decimal _tecoamont = 0;
                        if (_dsSelect.Tables[1].Rows[0]["TescoSelect"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["TescoSelect"].ToString() == "1")
                        {
                            lblTescoSelection.Text = "Voucher";
                            txtTescoSelectedId.Text = "1";
                            chkTescoVoucher.Checked = true;
                        }
                        else if (_dsSelect.Tables[1].Rows[0]["TescoSelect"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["TescoSelect"].ToString() == "2")
                        {
                            lblTescoSelection.Text = "Cash";
                            txtTescoSelectedId.Text = "2";
                            chkTescoCash.Checked = true;
                        }
                        else
                        {
                            lblTescoSelection.Text = "N/A";
                            txtTescoSelectedId.Text = "0";
                            chkTescoVoucher.Checked = false;
                            chkTescoCash.Checked = false;
                        }
                        if (_dsSelect.Tables.Count > 3 && _dsSelect.Tables[3].Rows.Count > 0)
                        {
                            if (_dsSelect.Tables[1].Rows[0]["TescoAmount"] != DBNull.Value && (decimal.TryParse(_dsSelect.Tables[1].Rows[0]["TescoAmount"].ToString(), out _tecoamont)))
                            {
                                txtTescoAmount.Text = _tecoamont.ToString("#0.00");
                                txtHideTescoWD.Text = _tecoamont.ToString("#0.00");
                                txtHideTescoWOD.Text = _tecoamont.ToString("#0.00");
                            }
                            else
                            {
                                txtTescoAmount.Text = "0.00";
                                txtHideTescoWD.Text = "0";
                                txtHideTescoWOD.Text = "0";
                            }
                        }
                        else
                        {
                            if (_dsSelect.Tables.Count > 1)
                            {
                                if (_dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString() != string.Empty)
                                {
                                    minPremium = _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString();
                                }


                            }
                            if (_dsSelect.Tables.Count > 2)
                            {
                                if (_dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"] != DBNull.Value && _dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"].ToString() != string.Empty)
                                {
                                    strCommence = _dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"].ToString();
                                }
                            }

                            if (!decimal.TryParse(minPremium, out _Premium))
                            {
                                _Premium = 0;
                            }

                            if (!DateTime.TryParse(strCommence, out _CoverCommDate))
                            {
                                _CoverCommDate = new DateTime();
                            }
                            ts = (_CoverCommDate.Date - _CurrentDate.Date);
                            days = ts.Days;
                            txtTescoAmount.Text = "0";

                            #region With Discount
                            txtHideTescoWD.Text = "0";
                            if (_Premium > 0 && _Premium <= 12000)
                            {
                                if (days > 60)
                                {
                                    txtTescoAmount.Text = "200";
                                    txtHideTescoWD.Text = "200";
                                }
                            }
                            else if (_Premium > 12000 && _Premium <= 15000)
                            {
                                if (days >= 15 && days <= 30)
                                {
                                    txtTescoAmount.Text = "200";
                                    txtHideTescoWD.Text = "200";
                                }
                                else if (days > 30 && days <= 60)
                                {
                                    txtTescoAmount.Text = "300";
                                    txtHideTescoWD.Text = "300";
                                }
                                else if (days > 60)
                                {
                                    txtTescoAmount.Text = "400";
                                    txtHideTescoWD.Text = "400";
                                }
                            }
                            else if (_Premium > 15000 && _Premium <= 20000)
                            {
                                if (days >= 15 && days <= 30)
                                {
                                    txtTescoAmount.Text = "300";
                                    txtHideTescoWD.Text = "300";
                                }
                                else if (days > 30 && days <= 60)
                                {
                                    txtTescoAmount.Text = "400";
                                    txtHideTescoWD.Text = "400";
                                }
                                else if (days > 60)
                                {
                                    txtTescoAmount.Text = "600";
                                    txtHideTescoWD.Text = "600";
                                }
                            }
                            else if (_Premium > 20000 && _Premium <= 30000)
                            {
                                if (days >= 15 && days <= 30)
                                {
                                    txtTescoAmount.Text = "400";
                                    txtHideTescoWD.Text = "400";
                                }
                                else if (days > 30 && days <= 60)
                                {
                                    txtTescoAmount.Text = "500";
                                    txtHideTescoWD.Text = "500";
                                }
                                else if (days > 60)
                                {
                                    txtTescoAmount.Text = "700";
                                    txtHideTescoWD.Text = "700";
                                }
                            }
                            else if (_Premium > 30000 && _Premium <= 40000)
                            {
                                if (days >= 15 && days <= 30)
                                {
                                    txtTescoAmount.Text = "500";
                                    txtHideTescoWD.Text = "500";
                                }
                                else if (days > 30 && days <= 60)
                                {
                                    txtTescoAmount.Text = "600";
                                    txtHideTescoWD.Text = "600";
                                }
                                else if (days > 60)
                                {
                                    txtTescoAmount.Text = "800";
                                    txtHideTescoWD.Text = "800";
                                }
                            }
                            else if (_Premium > 40000)
                            {
                                if (days >= 15 && days <= 30)
                                {
                                    txtTescoAmount.Text = "600";
                                    txtHideTescoWD.Text = "600";
                                }
                                else if (days > 30 && days <= 60)
                                {
                                    txtTescoAmount.Text = "700";
                                    txtHideTescoWD.Text = "700";
                                }
                                else if (days > 60)
                                {
                                    txtTescoAmount.Text = "1000";
                                    txtHideTescoWD.Text = "1000";
                                }
                            }
                            txtHideTescoWOD.Text = txtHideTescoWD.Text.Trim();
                            #endregion



                        }
                    }
                }
                else
                {
                    if (_dsSelect.Tables.Count > 1)
                    {
                        if (_dsSelect.Tables[1].Rows[0]["TescoSelect"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["TescoSelect"].ToString() == "1")
                        {
                            lblTescoSelection.Text = "Voucher";
                            txtTescoSelectedId.Text = "1";
                            chkTescoVoucher.Checked = true;
                        }
                        else if (_dsSelect.Tables[1].Rows[0]["TescoSelect"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["TescoSelect"].ToString() == "2")
                        {
                            lblTescoSelection.Text = "Cash";
                            txtTescoSelectedId.Text = "2";
                            chkTescoCash.Checked = true;
                        }
                        else
                        {
                            lblTescoSelection.Text = "N/A";
                            txtTescoSelectedId.Text = "0";
                            chkTescoVoucher.Checked = false;
                            chkTescoCash.Checked = false;
                        }

                        if (_dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString() != string.Empty)
                        {
                            minPremium = _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString();
                        }
                    }
                    if (_dsSelect.Tables.Count > 1)
                    {
                        if (_dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"] != DBNull.Value && _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString() != string.Empty)
                        {
                            minPremium = _dsSelect.Tables[1].Rows[0]["FinalAnnualPremium"].ToString();
                        }


                    }
                    if (_dsSelect.Tables.Count > 2)
                    {
                        if (_dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"] != DBNull.Value && _dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"].ToString() != string.Empty)
                        {
                            strCommence = _dsSelect.Tables[2].Rows[0]["CoverageCommenceDate"].ToString();
                        }
                    }

                    if (!decimal.TryParse(minPremium, out _Premium))
                    {
                        _Premium = 0;
                    }

                    if (!DateTime.TryParse(strCommence, out _CoverCommDate))
                    {
                        _CoverCommDate = new DateTime();
                    }
                    ts = (_CoverCommDate.Date - _CurrentDate.Date);
                    days = ts.Days;
                    txtTescoAmount.Text = "0";

                    #region With Discount
                    txtHideTescoWD.Text = "0";
                    if (_Premium > 0 && _Premium <= 12000)
                    {
                        if (days > 60)
                        {
                            txtTescoAmount.Text = "200";
                            txtHideTescoWD.Text = "200";
                        }
                    }
                    else if (_Premium > 12000 && _Premium <= 15000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtTescoAmount.Text = "200";
                            txtHideTescoWD.Text = "200";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtTescoAmount.Text = "300";
                            txtHideTescoWD.Text = "300";
                        }
                        else if (days > 60)
                        {
                            txtTescoAmount.Text = "400";
                            txtHideTescoWD.Text = "400";
                        }
                    }
                    else if (_Premium > 15000 && _Premium <= 20000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtTescoAmount.Text = "300";
                            txtHideTescoWD.Text = "300";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtTescoAmount.Text = "400";
                            txtHideTescoWD.Text = "400";
                        }
                        else if (days > 60)
                        {
                            txtTescoAmount.Text = "600";
                            txtHideTescoWD.Text = "600";
                        }
                    }
                    else if (_Premium > 20000 && _Premium <= 30000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtTescoAmount.Text = "400";
                            txtHideTescoWD.Text = "400";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtTescoAmount.Text = "500";
                            txtHideTescoWD.Text = "500";
                        }
                        else if (days > 60)
                        {
                            txtTescoAmount.Text = "700";
                            txtHideTescoWD.Text = "700";
                        }
                    }
                    else if (_Premium > 30000 && _Premium <= 40000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtTescoAmount.Text = "500";
                            txtHideTescoWD.Text = "500";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtTescoAmount.Text = "600";
                            txtHideTescoWD.Text = "600";
                        }
                        else if (days > 60)
                        {
                            txtTescoAmount.Text = "800";
                            txtHideTescoWD.Text = "800";
                        }
                    }
                    else if (_Premium > 40000)
                    {
                        if (days >= 15 && days <= 30)
                        {
                            txtTescoAmount.Text = "600";
                            txtHideTescoWD.Text = "600";
                        }
                        else if (days > 30 && days <= 60)
                        {
                            txtTescoAmount.Text = "700";
                            txtHideTescoWD.Text = "700";
                        }
                        else if (days > 60)
                        {
                            txtTescoAmount.Text = "1000";
                            txtHideTescoWD.Text = "1000";
                        }
                    }
                    txtHideTescoWOD.Text = txtHideTescoWD.Text.Trim();
                    #endregion


                }

                decimal _tescowd = 0;
                decimal _tescowod = 0;
                decimal _premiumwd = 0;
                decimal _premiumwod = 0;
                decimal _showpremiumwd = 0;
                decimal _showpremiumwod = 0;
                if (!decimal.TryParse(txtHideTescoWD.Text, out _tescowd))
                {
                    _tescowd = 0;
                }
                if (!decimal.TryParse(txtHideTescoWOD.Text, out _tescowod))
                {
                    _tescowod = 0;
                }
                if (!decimal.TryParse(txtWDPremium.Text, out _premiumwd))
                {
                    _premiumwd = 0;
                }
                if (!decimal.TryParse(txtWODPremium.Text, out _premiumwod))
                {
                    _premiumwod = 0;
                }

                _showpremiumwd = (_premiumwd - _tescowd);
                _showpremiumwod = (_premiumwod - _tescowod);

                txtAFTPremiumWD.Text = _showpremiumwd.ToString("#0.00");
                txtAFTPremiumWOD.Text = _showpremiumwod.ToString("#0.00");

                if (txtIsWD.Text != string.Empty && txtIsWD.Text == "0")
                {
                    txtTescoAmount.Text = txtHideTescoWOD.Text;
                }
                else
                {
                    txtTescoAmount.Text = txtHideTescoWD.Text;
                }
            }
        }
        txtTescoAmountSelection.Text = txtTescoAmount.Text;
        if (txtIsWD.Text != string.Empty && txtIsWD.Text == "0")
        {
            if (chkTescoCash.Checked)
            {
                txtFinalPrice.Text = txtAFTPremiumWOD.Text.Trim();
                lblUpPremium.Text = txtAFTPremiumWOD.Text.Trim();
            }
            else
            {
                txtFinalPrice.Text = txtWODPremium.Text.Trim();
                lblUpPremium.Text = txtWODPremium.Text.Trim();
            }
            lblPayPremium.Text = txtWODPremium.Text.Trim();
            lblPayPremiumAfterTescoCash.Text = txtAFTPremiumWOD.Text.Trim();
        }
        else
        {
            if (chkTescoCash.Checked)
            {
                txtFinalPrice.Text = txtAFTPremiumWD.Text.Trim();
                lblUpPremium.Text = txtAFTPremiumWD.Text.Trim();
            }
            else
            {
                txtFinalPrice.Text = txtWDPremium.Text.Trim();
                lblUpPremium.Text = txtWDPremium.Text.Trim();
            }
            lblPayPremium.Text = txtWDPremium.Text.Trim();
            lblPayPremiumAfterTescoCash.Text = txtAFTPremiumWD.Text.Trim();
        }

        #region Get Final Approve Premium
        MyDatabase _myDB = new MyDatabase("GG_MCDBConnectionString");
        txtCashierApproved.Text = "0";
        string _strCashierApprovedPremium = "0";
        decimal _dCashierApprovedPremium = 0;
        string strSelectSql = "SELECT Approved, ApprovedPremium FROM tblMerchantBrokerPremium WHERE Info1 = '" + lblUpRefNo.Text.Trim() + "' AND SelectedStatus = 1 AND CarId = " + txtCarId.Text.Trim();
        DataTable _SelectItemResult = _myDB.GetDataTable(strSelectSql);
        if (_SelectItemResult != null && _SelectItemResult.Rows.Count > 0)
        {
            if (_SelectItemResult.Rows[0]["Approved"] != DBNull.Value)
            {
                txtCashierApproved.Text = _SelectItemResult.Rows[0]["Approved"].ToString();
            }
            if (_SelectItemResult.Rows[0]["ApprovedPremium"] != DBNull.Value)
            {
                _strCashierApprovedPremium = _SelectItemResult.Rows[0]["ApprovedPremium"].ToString();
            }
        }
        if (txtCashierApproved.Text.Trim() != "0")
        {
            if (decimal.TryParse(_strCashierApprovedPremium, out _dCashierApprovedPremium))
            {
                txtFinalPrice.Text = _dCashierApprovedPremium.ToString("#0.00");
                lblUpPremium.Text = txtFinalPrice.Text.Trim();
            }
        }
        #endregion

        txtFinalApprovalPremium.Text = txtFinalPrice.Text.Trim();
        lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
        lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();

        decimal _collected = 0;
        decimal _refund = 0;
        decimal _final = 0;
        if (!decimal.TryParse(txtTotalCollectedAmount.Text.Trim(), out _collected))
        {
            _collected = 0;
        }
        if (!decimal.TryParse(txtTotalRefundAmount.Text.Trim(), out _refund))
        {
            _refund = 0;
        }
        if (!decimal.TryParse(txtFinalPrice.Text.Trim(), out _final))
        {
            _final = 0;
        }

        txtBalanceAmount.Text = (_final - _collected).ToString("#0.00");

        if (txtTescoAmount.Text != string.Empty && Convert.ToSingle(txtTescoAmount.Text.Trim()) <= 0)
        {
            divTescoCash.Visible = false;
            chkTescoCash.Checked = false;
            chkTescoVoucher.Checked = false;
            chkTescoCash.Enabled = false;
            chkTescoVoucher.Enabled = false;
        }
        else
        {
            divTescoCash.Visible = true;
            lblPayPremiumAfterTescoCashTitle.Text = Resources.General.Premium + " (After Tesco Cash)";
            chkTescoCash.Enabled = true;
            chkTescoVoucher.Enabled = true;
        }
        if (txtCashierApproved.Text != "0")
        {
            chkTescoVoucher.Enabled = false;
            chkTescoCash.Enabled = false;
        }
        decimal Tesco = 0;
        if (txtTescoSelectedId.Text == "0" && decimal.TryParse(txtTescoAmount.Text.Trim(), out Tesco))
        {
            if (Tesco <= 0 || (Tesco > 0 && Session[General.UserRole].ToString() == "300"))
            {
                tdTescoAmount.BgColor = "#D8D8D8";
                tdTescoAmountSelection.BgColor = "#D8D8D8";
                tdAFTPremiumWD.BgColor = "#D8D8D8";
                tdAFTPremiumWOD.BgColor = "#D8D8D8";

                txtTescoAmount.BackColor = System.Drawing.Color.LightGray;
                txtTescoAmountSelection.BackColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWD.BackColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWOD.BackColor = System.Drawing.Color.LightGray;

                txtTescoAmount.ForeColor = System.Drawing.Color.LightGray;
                txtTescoAmountSelection.ForeColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWD.ForeColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWOD.ForeColor = System.Drawing.Color.LightGray;

                txtTescoAmount.BorderColor = System.Drawing.Color.LightGray;
                txtTescoAmountSelection.BorderColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWD.BorderColor = System.Drawing.Color.LightGray;
                txtAFTPremiumWOD.BorderColor = System.Drawing.Color.LightGray;
            }
        }
    }

    public void LoadPaymentCompletedStatus()
    {
        try
        {
            txtPaymentStatus.Text = "0";
            DateTime ApproveDate = dateTimeNow;
            MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
            string strSql = @"SELECT TransactionId,CarId,QuoteRefNo,ProviderCompanyId,Remarks,ModifiedDate FROM tblMerchantTransaction ";
            strSql += " WHERE TransactionTypeId = 100 AND [Status] = 1 AND CarId =  " + txtCarId.Text;
            DataTable _dtTransaction = _db.GetDataTable(strSql);
            if (_dtTransaction != null && _dtTransaction.Rows.Count > 0)
            {
                txtTransactionId.Text = "-1";
                if (_dtTransaction.Rows[0]["TransactionId"] != DBNull.Value && _dtTransaction.Rows[0]["TransactionId"].ToString() != string.Empty)
                {
                    txtTransactionId.Text = _dtTransaction.Rows[0]["TransactionId"].ToString();
                    txtPaymentStatus.Text = "1";
                }
                if (_dtTransaction.Rows[0]["ModifiedDate"] != DBNull.Value && _dtTransaction.Rows[0]["ModifiedDate"].ToString() != string.Empty)
                {
                    if (!DateTime.TryParse(_dtTransaction.Rows[0]["ModifiedDate"].ToString(), out ApproveDate))
                    {
                        ApproveDate = dateTimeNow;
                    }
                    lblPaymentStatusMessage.Text = "Payment Completed Status Updated on " + ApproveDate.ToString("dd/MMM/yyyy hh:mm tt");
                }
            }
            if (txtPaymentStatus.Text.Trim() == "0")
            {
                lblPaymentStatusMessage.Text = "Payment Completed Status Not Updated Yet!";
            }
        }
        catch (Exception ex)
        {
        }
    }

    public bool CheckPaymentCompletedStatusDate()
    {
        try
        {
            bool ISValidtoDelete = true;
            DateTime TodayDate = dateTimeNow;
            DateTime ApproveDate = dateTimeNow;
            MyDatabase _db = new MyDatabase("GG_MCDBConnectionString");
            string strSql = @"SELECT TransactionId,CarId,QuoteRefNo,ProviderCompanyId,Remarks,ModifiedDate FROM tblMerchantTransaction ";
            strSql += " WHERE TransactionTypeId = 100 AND [Status] = 1 AND CarId =  " + txtCarId.Text;
            DataTable _dtTransaction = _db.GetDataTable(strSql);
            if (_dtTransaction != null && _dtTransaction.Rows.Count > 0)
            {
                if (_dtTransaction.Rows[0]["ModifiedDate"] != DBNull.Value && _dtTransaction.Rows[0]["ModifiedDate"].ToString() != string.Empty)
                {
                    if (!DateTime.TryParse(_dtTransaction.Rows[0]["ModifiedDate"].ToString(), out ApproveDate))
                    {
                        ApproveDate = dateTimeNow;
                    }
                }
            }
            TimeSpan ts;
            Int32 days = 0;
            ts = (TodayDate.Date - ApproveDate.Date);
            days = ts.Days;
            if (days >= 15)
            {
                ISValidtoDelete = false;
            }
            return ISValidtoDelete;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    protected void chkTescoCash_CheckedChanged(object sender, EventArgs e)
    {
        if (txtCashierApproved.Text == "0")
        {
            if (chkTescoCash.Checked)
            {
                chkTescoVoucher.Checked = false;
                txtAmount.Text = lblPayPremiumAfterTescoCash.Text;
                txtFinalPrice.Text = lblPayPremiumAfterTescoCash.Text;
                txtAmount.ReadOnly = true;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtAFTPremiumWD.Text.Trim();
                lblUpPremiumWOD.Text = txtAFTPremiumWOD.Text.Trim();
            }
            else if (chkTescoVoucher.Checked)
            {
                chkTescoCash.Checked = false;
                txtAmount.Text = lblPayPremium.Text;
                txtFinalPrice.Text = lblPayPremium.Text;
                txtAmount.ReadOnly = true;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
                lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();
            }
            else
            {
                txtAmount.Text = lblPayPremium.Text;
                txtFinalPrice.Text = lblPayPremium.Text;
                txtAmount.ReadOnly = false;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
                lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();
            }

            decimal _collected = 0;
            decimal _refund = 0;
            decimal _final = 0;
            if (!decimal.TryParse(txtTotalCollectedAmount.Text.Trim(), out _collected))
            {
                _collected = 0;
            }
            if (!decimal.TryParse(txtTotalRefundAmount.Text.Trim(), out _refund))
            {
                _refund = 0;
            }
            if (!decimal.TryParse(txtFinalPrice.Text.Trim(), out _final))
            {
                _final = 0;
            }

            txtBalanceAmount.Text = (_final - _collected).ToString("#0.00");
            txtFinalApprovalPremium.Text = txtFinalPrice.Text.Trim();
        }
    }

    protected void chkTescoVoucher_CheckedChanged(object sender, EventArgs e)
    {
        if (txtCashierApproved.Text == "0")
        {
            if (chkTescoVoucher.Checked)
            {
                chkTescoCash.Checked = false;
                txtAmount.Text = lblPayPremium.Text;
                txtFinalPrice.Text = lblPayPremium.Text;
                txtAmount.ReadOnly = true;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
                lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();
            }
            else if (chkTescoCash.Checked)
            {
                chkTescoVoucher.Checked = false;
                txtAmount.Text = lblPayPremiumAfterTescoCash.Text;
                txtFinalPrice.Text = lblPayPremiumAfterTescoCash.Text;
                txtAmount.ReadOnly = true;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtAFTPremiumWD.Text.Trim();
                lblUpPremiumWOD.Text = txtAFTPremiumWOD.Text.Trim();
            }
            else
            {
                txtAmount.ReadOnly = false;

                lblUpPremium.Text = txtFinalPrice.Text.Trim();
                lblUpPremiumWD.Text = txtWDPremium.Text.Trim();
                lblUpPremiumWOD.Text = txtWODPremium.Text.Trim();
            }

            decimal _collected = 0;
            decimal _refund = 0;
            decimal _final = 0;
            if (!decimal.TryParse(txtTotalCollectedAmount.Text.Trim(), out _collected))
            {
                _collected = 0;
            }
            if (!decimal.TryParse(txtTotalRefundAmount.Text.Trim(), out _refund))
            {
                _refund = 0;
            }
            if (!decimal.TryParse(txtFinalPrice.Text.Trim(), out _final))
            {
                _final = 0;
            }

            txtBalanceAmount.Text = (_final - _collected).ToString("#0.00");
            txtFinalApprovalPremium.Text = txtFinalPrice.Text.Trim();
        }
    }

    #region Contact Quote Tab

    protected void btnGoToView_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtCEId.Text != string.Empty && txtCarId.Text != string.Empty)
            {
                string _strReturnMessage = string.Empty;
                string tabs = "&tabid=" + hidLastTab.Value;
                _strReturnMessage = "CEId=" + txtCEId.Text.Trim() + "&CarId=" + txtCarId.Text + tabs;
                Response.Redirect("MerchantManualQuote.aspx?" + _strReturnMessage);
            }
        }
        catch (Exception Ex)
        {

        }
    }

    #endregion


    public bool SendTestAdmin()
    {
        bool _result = true;
        string mailBody = "";
        string _emailTitle = "";
        string _toemail = "";
        string _ccemail = "";
        string _bccemail = "";
        _emailTitle = "SMTP Testing";
        mailBody = "Hello World.! Admin2 SMTP Testing Successful";
        _toemail = "kandasamy.sakthivel@comparexpress.com";

        _result = MyMailManager.SendCXMail(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString());

        return _result;
    }

}
